【Azure 环境】各种语言版本或命令,发送HTTP/HTTPS的请求合集

问题描述

写代码的过程中,时常遇见要通过代码请求其他HTTP,HTTPS的情况,以下是收集各种语言的请求发送,需要使用的代码或命令

一:PowerShell

Invoke-WebRequest https://docs.azure.cn/zh-cn/

命令说明https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7

二:curl

curl https://docs.azure.cn/zh-cn/

命令说明https://curl.haxx.se/docs/httpscripting.html

三:C#

//添加Http的引用
using
System.Net.Http;
//使用HttpClient对象发送Get请求
using (HttpClient httpClient = new HttpClient()) {   var url = $"https://functionapp120201013155425.chinacloudsites.cn/api/HttpTrigger1?name={name}";   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, url);   httpRequest.Headers.Add("Accept", "application/json, text/plain, */*");   var response = httpClient.SendAsync(httpRequest).Result;   string responseContent = response.Content.ReadAsStringAsync().Result;   return responseContent; } //POST using (HttpClient httpClient = new HttpClient()) {   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, botNotifySendApi);   httpRequest.Headers.Add("Accept", "application/json, text/plain, */*");   httpRequest.Headers.Add("Authorization", apimauthorization);   var content = new StringContent(messageBody, Encoding.UTF8, "application/json");   httpRequest.Content = content;   var response = await httpClient.SendAsync(httpRequest);   string responseContent = await response.Content.ReadAsStringAsync();   if (response.StatusCode == System.Net.HttpStatusCode.OK)   {     //responseContent   } }

//POST 2

using (HttpClient httpClient = new HttpClient()) { string messageBody = "{\"vehicleType\": \"train\",\"maxSpeed\": 125,\"avgSpeed\": 90,\"speedUnit\": \"mph in code\"}"; var url = $"https://test02.azure-api.cn/echo/resource"; HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post, url); httpRequest.Headers.Add("Accept", "application/json, text/plain, */*"); var content = new StringContent(messageBody, Encoding.UTF8, "application/json"); httpRequest.Content = content; var response = httpClient.SendAsync(httpRequest).Result; responseContent = response.Content.ReadAsStringAsync().Result; }

 

代码说明:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netcore-3.1

四:Java

pom.xml

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.10</version>
</dependency>

GET/POST

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientExample {

    // one instance, reuse
    private final CloseableHttpClient httpClient = HttpClients.createDefault();

    public static void main(String[] args) throws Exception {

        HttpClientExample obj = new HttpClientExample();

        try {
            System.out.println("Send Http GET request");
            obj.sendGet();

            System.out.println("Send Http POST request");
            obj.sendPost();
        } finally {
            obj.close();
        }
    }

    private void close() throws IOException {
        httpClient.close();
    }

    private void sendGet() throws Exception {

        HttpGet request = new HttpGet("https://docs.azure.cn/zh-cn/");

        // add request headers
        // request.addHeader("customkey", "test");try (CloseableHttpResponse response = httpClient.execute(request)) {

            // Get HttpResponse Status
            System.out.println(response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            Header headers = entity.getContentType();
            System.out.println(headers);

            if (entity != null) {
                // return it as a String
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }

        }

    }

    private void sendPost() throws Exception {

        HttpPost post = new HttpPost("https://httpbin.org/post");

        // add request parameter, form parameters
        List<NameValuePair> urlParameters = new ArrayList<>();
        urlParameters.add(new BasicNameValuePair("username", "test"));
        urlParameters.add(new BasicNameValuePair("password", "admin"));
        urlParameters.add(new BasicNameValuePair("custom", "test"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(post)) {

            System.out.println(EntityUtils.toString(response.getEntity()));
        }
    }
}

代码说明:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/HttpGet.html

 

五:Python

import requests

x = requests.get('https://docs.azure.cn/zh-cn/')

print(x.text)

代码说明:https://www.w3schools.com/python/module_requests.asp

六:PHP

//Additionally consider two more PHP functions that can be coded in a single line.

$data = file_get_contents ($my_url);

//This will return the raw data stream from the URL.

$xml = simple_load_file($my_url);

curl in PHP

// create & initialize a curl session
$curl = curl_init();

// set our url with curl_setopt()
curl_setopt($curl, CURLOPT_URL, "api.example.com");

// return the transfer as a string, also with setopt()
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// curl_exec() executes the started curl session
// $output contains the output string
$output = curl_exec($curl);

// close curl resource to free up system resources
// (deletes the variable made by curl_init)
curl_close($curl);

代码说明: https://weichie.com/blog/curl-api-calls-with-php/

七:JavaScript

var request = new XMLHttpRequest()

request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
  // Begin accessing JSON data here
  var data = JSON.parse(this.response)

  if (request.status >= 200 && request.status < 400) {
    data.forEach((movie) => {
      console.log(movie.title)
    })
  } else {
    console.log('error')
  }
}

request.send()

代码说明:https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/

八:jQuery.ajax()

var menuId = $( "ul.nav" ).first().attr( "id" );
var request = $.ajax({
  url: "script.php",
  method: "POST",
  data: { id : menuId },
  dataType: "html"
});
 
request.done(function( msg ) {
  $( "#log" ).html( msg );
});
 
request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

代码说明: https://api.jquery.com/jquery.ajax/

jQuery 2:

<script src="~/lib/jquery/dist/jquery.js"></script>

<script>

    var request = $.ajax({
        url: "https://test01.azure-api.cn/echo/resource",
        type: "POST",
        headers: {
            "x-zumo-application": "test"
        },
        data: {
            vehicleType: "train",
            maxSpeed: 125,
            avgSpeed: 90,
            speedUnit: "mph"
        },
        dataType: "text"
    });

    request.done(function (msg) {
        console.log(msg);
    });

    request.fail(function (jqXHR, textStatus) {
        console.log("Request failed: " + textStatus);
    });

</script>

 

九:Go

resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
...
resp, err := http.PostForm("http://example.com/form",
    url.Values{"key": {"Value"}, "id": {"123"}})

代码说明:https://golang.org/pkg/net/http/

 

posted @ 2020-11-05 20:12  路边两盏灯  阅读(358)  评论(1编辑  收藏  举报