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

 

相关文章
|
14天前
|
监控 网络协议 应用服务中间件
【Tomcat源码分析】从零开始理解 HTTP 请求处理 (第一篇)
本文详细解析了Tomcat架构中复杂的`Connector`组件。作为客户端与服务器间沟通的桥梁,`Connector`负责接收请求、封装为`Request`和`Response`对象,并传递给`Container`处理。文章通过四个关键问题逐步剖析了`Connector`的工作原理,并深入探讨了其构造方法、`init()`与`start()`方法。通过分析`ProtocolHandler`、`Endpoint`等核心组件,揭示了`Connector`初始化及启动的全过程。本文适合希望深入了解Tomcat内部机制的读者。欢迎关注并点赞,持续更新中。如有问题,可搜索【码上遇见你】交流。
【Tomcat源码分析】从零开始理解 HTTP 请求处理 (第一篇)
|
5天前
|
前端开发 JavaScript 数据库
https页面加载http资源的解决方法
https页面加载http资源的解决方法
13 7
|
3天前
|
JSON Java 数据格式
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
9 1
|
19天前
|
安全 应用服务中间件 网络安全
简单比较 http https http2,我们要如何把http升级为https
【9月更文挑战第13天】本文对比了HTTP、HTTPS和HTTP/2的特点与适用场景。HTTP以明文传输,适合低安全要求的环境;HTTPS通过SSL/TLS加密,适用于电子商务等安全要求高的场景;HTTP/2采用二进制格式和多路复用,适合高性能Web应用。文章还详细介绍了将HTTP升级为HTTPS的步骤,包括申请和安装SSL证书、配置Web服务器、重定向HTTP流量到HTTPS以及测试HTTPS功能。升级到HTTPS可提高数据安全性和用户信任度。
52 13
|
20天前
|
安全 网络安全 数据安全/隐私保护
HTTP与HTTPS协议区别及应用场景
在互联网高速发展的今天,HTTP与HTTPS作为数据传输的基石,作用至关重要。HTTP允许客户端与服务器间传输超文本文档,但其数据传输过程未加密,存在安全隐患;HTTPS则在此基础上加入了SSL/TLS协议,实现了数据加密传输,增强了安全性,广泛应用于电子商务、网上银行、政府网站及社交媒体平台等涉及敏感信息传输的领域,有效保护了用户隐私和数据安全。随着网络安全意识提升,HTTPS正逐渐成为主流。
|
23天前
|
JSON JavaScript 前端开发
Haskell中的数据交换:通过http-conduit发送JSON请求
Haskell中的数据交换:通过http-conduit发送JSON请求
|
Web App开发 存储 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
      前段时间公司hadoop集群宕机,发现是namenode磁盘满了, 清理出部分空间后,重启集群时,重启失败。 又发现集群Secondary namenode 服务也恰恰坏掉,导致所有的操作log持续写入edits.new 文件,等集群宕机的时候文件大小已经达到了丧心病狂的70G+..重启集群报错 加载edits文件失败。
899 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
总结和计划总是让人喜悦或镇痛,一方面以前一段时间没有荒废,能给现在的行动以信心,另一方面看到一年的时间并不能完成很多事情,需要抓紧时间。
610 0
|
Web App开发 监控 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
系统的升级涉及各个架构组件,细节很多。常年累月的修修补补使老系统积累了很多问题。 系统升级则意味着需要repair之前埋下的雷,那为何还要升级,可以考虑以下几个方面 成熟老系统常见问题: 1. 缺乏文档(这应该是大小公司都存在的问题。
617 0

热门文章

最新文章

下一篇
无影云桌面