【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/

 

相关文章
|
2月前
|
缓存 安全 网络协议
HTTP和HTTPS的区别有哪些?
本文简要总结了 HTTP 和 HTTPS 的区别,从概念、端口、连接方式、使用场景、安全性等多个角度进行了对比。HTTP 是无状态的、无连接的应用层协议,适用于一般性网站和性能要求较高的应用;HTTPS 则通过 SSL/TLS 层提供加密、认证和完整性保护,适用于涉及敏感信息和高安全性的场景。文章还讨论了两者在性能上的差异,包括握手和加密开销、缓存效果以及 HTTP/2 的多路复用技术。最终,根据具体需求选择合适的协议能够更好地平衡安全性和性能。
290 2
HTTP和HTTPS的区别有哪些?
|
1月前
|
前端开发 JavaScript 安全
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第27天】本文介绍了HTTP/2和HTTPS在前端性能调优中的应用。通过多路复用、服务器推送和头部压缩等特性,HTTP/2显著提升了Web性能。同时,HTTPS确保了数据传输的安全性。文章提供了示例代码,展示了如何使用Node.js创建一个HTTP/2服务器。
58 3
|
25天前
|
Dubbo 安全 应用服务中间件
Apache Dubbo 正式发布 HTTP/3 版本 RPC 协议,弱网效率提升 6 倍
在 Apache Dubbo 3.3.0 版本之后,官方推出了全新升级的 Triple X 协议,全面支持 HTTP/1、HTTP/2 和 HTTP/3 协议。本文将围绕 Triple 协议对 HTTP/3 的支持进行详细阐述,包括其设计目标、实际应用案例、性能测试结果以及源码架构分析等内容。
|
1月前
|
缓存 安全 网络安全
HTTP/2与HTTPS在Web加速中的应用
HTTP/2与HTTPS在Web加速中的应用
|
4天前
|
安全 网络安全 数据安全/隐私保护
第六问:http和https区别与联系
HTTP 和 HTTPS 是现代网络通信中的两种重要协议。HTTP 是明文传输协议,无加密功能;HTTPS 在 HTTP 基础上加入 SSL/TLS 加密层,提供数据加密、身份验证和数据完整性保障。HTTP 适用于非敏感信息传输,如新闻网站;HTTPS 适用于在线支付、账户登录等需要保护用户数据的场景。
18 0
|
1月前
|
前端开发 JavaScript 数据库
https页面加载http资源的解决方法
https页面加载http资源的解决方法
58 5
|
1月前
|
网络协议 安全 Go
Go语言进行网络编程可以通过**使用TCP/IP协议栈、并发模型、HTTP协议等**方式
【10月更文挑战第28天】Go语言进行网络编程可以通过**使用TCP/IP协议栈、并发模型、HTTP协议等**方式
51 13
|
1月前
|
前端开发 安全 应用服务中间件
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第26天】随着互联网的快速发展,前端性能调优成为开发者的重要任务。本文探讨了HTTP/2与HTTPS在前端性能优化中的应用,介绍了二进制分帧、多路复用和服务器推送等特性,并通过Nginx配置示例展示了如何启用HTTP/2和HTTPS,以提升Web应用的性能和安全性。
37 3
|
1月前
|
前端开发 JavaScript 数据库
https页面加载http资源的解决方法
https页面加载http资源的解决方法
58 4
|
1月前
|
安全 前端开发 JavaScript
http和https
【10月更文挑战第22天】http和https
43 2

热门文章

最新文章

下一篇
DataWorks