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

简介: 【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/

 

目录
打赏
0
0
0
0
203
分享
相关文章
HTTP常见的请求方法、响应状态码、接口规范介绍
本文详细介绍了HTTP常见的请求方法、响应状态码和接口规范。通过理解和掌握这些内容,开发者可以更好地设计和实现W
228 83
动态URL构建与HTTP请求的Kotlin实现
动态URL构建与HTTP请求的Kotlin实现
|
26天前
|
API
掌握 HTTP 请求的艺术:理解 cURL GET 语法
掌握 cURL GET 请求的语法和使用方法是 Web 开发和测试中的基本技能。通过灵活运用 cURL 提供的各种选项,可以高效地与 API 进行交互、调试网络请求,并自动化日常任务。希望本文能帮助读者更好地理解和使用 cURL,提高工作效率和代码质量。
36 7
Objective-C开发:从HTTP请求到文件存储的实战
Objective-C开发:从HTTP请求到文件存储的实战
探索网络模型与协议:从OSI到HTTPs的原理解析
OSI七层网络模型和TCP/IP四层模型是理解和设计计算机网络的框架。OSI模型包括物理层、数据链路层、网络层、传输层、会话层、表示层和应用层,而TCP/IP模型则简化为链路层、网络层、传输层和 HTTPS协议基于HTTP并通过TLS/SSL加密数据,确保安全传输。其连接过程涉及TCP三次握手、SSL证书验证、对称密钥交换等步骤,以保障通信的安全性和完整性。数字信封技术使用非对称加密和数字证书确保数据的机密性和身份认证。 浏览器通过Https访问网站的过程包括输入网址、DNS解析、建立TCP连接、发送HTTPS请求、接收响应、验证证书和解析网页内容等步骤,确保用户与服务器之间的安全通信。
247 3
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
HTTPS协议是**一种通过计算机网络进行安全通信的传输协议
110 11
HTTPS协议的历史发展
HTTPS协议的历史发展
134 8
判断一个网站是否使用HTTPS协议
判断一个网站是否使用HTTPS协议
559 4
HTTPS网络通信协议揭秘:WEB网站安全的关键技术
HTTPS网络通信协议揭秘:WEB网站安全的关键技术
405 4
HTTPS网络通信协议揭秘:WEB网站安全的关键技术