问题描述

写代码的过程中,时常遇见要通过代码请求其他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/

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

  1. Linux命令发送Http GET/POST请求

    Get请求 curl命令模拟Get请求: 1.使用curl命令: curl "http://www.baidu.com" 如果这里的URL指向的是一个文件或者一幅图都可以直接下载到 ...

  2. PHP 命令行模式实战之cli+mysql 模拟队列批量发送邮件(在Linux环境下PHP 异步执行脚本发送事件通知消息实际案例)

    源码地址:https://github.com/Tinywan/PHP_Experience 测试环境配置: 环境:Windows 7系统 .PHP7.0.Apache服务器 PHP框架:ThinkP ...

  3. 非域环境下搭建自动故障转移镜像无法将 ALTER DATABASE 命令发送到远程服务器实例的解决办法

    非域环境下搭建自动故障转移镜像无法将 ALTER DATABASE 命令发送到远程服务器实例的解决办法 环境:非域环境 因为是自动故障转移,需要加入见证,事务安全模式是,强安全FULL模式 做到最后一 ...

  4. [Swift通天遁地]五、高级扩展-(13)图片资源本地化设置:根据不同的语言环境显示不同语言版本图片

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs. ...

  5. 【Azure 环境】使用Microsoft Graph PS SDK 登录到中国区Azure, 命令Connect-MgGraph -Environment China xxxxxxxxx 遇见登录错误

    问题描述 通过PowerShell 连接到Microsoft Graph 中国区Azure,一直出现AADSTS700016错误, 消息显示 the specific application was ...

  6. Qt 编写应用支持多语言版本--一个GUI应用示例

    简介 上一篇博文已经说过如何编写支持多语言的Qt 命令行应用,这一篇说说Qt GUI 应用多语言支持的坑. 本人喜欢用代码来写布局,而不是用 Qt Designer 来设计布局,手写布局比 Qt De ...

  7. C#环境变量配置及csc命令详解(转自cy88310)

     C#环境变量设置步骤: 在桌面右击[我的电脑]->[属性]->[高级]->[环境变量] 在下面的系统变量栏点击"新建" 变量名输入"csc" ...

  8. MAC下 JDK环境配置、版本切换以及ADB环境配置

    网上方法,自己总结:亲测可行! 一.JDK环境配置.版本切换: 通过命令’jdk6′, ‘jdk7′,’jdk8’轻松切换到对应的Java版本: 1.首先安装所有的JDk:* Mac自带了的JDK6, ...

  9. Linux下查看内核、CPU、内存及各组件版本的命令和方法

    Linux下查看内核.CPU.内存及各组件版本的命令和方法 Linux查看内核版本: uname -a                        more /etc/*release       ...

  10. Azure环境中Nginx高可用性和部署架构设计

    前几篇文章介绍了Nginx的应用.动态路由.配置.在实际生产环境部署时,我们需要同时考虑Nginx的高可用性和部署架构. Nginx自身不支持集群以保证自身的高可用性,商业版本的Nginx+推荐: T ...

随机推荐

  1. Mysql Server System Variables [官网资料]

    5.1.7 Server System Variables The MySQL server maintains many system variables that configure its op ...

  2. 装elemnetUI中用户头像上传

    组件.vue 在使用的时候,入股想出现边框.要自己在添加一个类哈 自己还有在添加一个哈 .avatar-uploader { border:1px solid red; width: 178px; h ...

  3. docker的架构及工作原理(详解)

    目录 一.docker架构图 二.Client 客户端 三.Host 主机(docker引擎) 四.Image 镜像 五.Container 容器 六.镜像分层 可写的容器层 七.Volume 数据卷 ...

  4. vim 从嫌弃到依赖(3)——vim 普通模式

    在上一篇中,我们提到vim的几种模式,并且给出了一些基本的操作命令,包括移动光标,删除.替换操作.并且给出了几个重要的公式,理解这个公式对于理解vim和提高使用vim的效率来说至关重要.所以在这篇文章 ...

  5. 2.6 Windows驱动开发:使用IO与DPC定时器

    本章将继续探索驱动开发中的基础部分,定时器在内核中同样很常用,在内核中定时器可以使用两种,即IO定时器,以及DPC定时器,一般来说IO定时器是DDK中提供的一种,该定时器可以为间隔为N秒做定时,但如果 ...

  6. vue + elementui 分页切换页面,缓存页码

    问题场景 列表页面输入查询条件,选择第3页,点击详情进入详情页,从详情页返回时,默认列表页面页码重置为1:此时想要缓存该页码,有两种方式:可按业务场景使用 方式一:用vue自带的 keep-alive ...

  7. (转)时代的见证:集成更新的Windows 7旗舰版、专业版镜像

    制作缘起:微软曾于2019年提供过两份内部集成更新的英文旗舰版.专业版镜像(参见:集成IE11+最新补丁:微软新版Windows 7镜像泄露),方便用户安装,缩短更新过程.经我们下载安装研究发现,这两 ...

  8. 使用DoraCloud搭建支持统信UOS桌面的信创云桌面系统

    信创云桌面 信创云桌面采用国产的芯片,支持国产的桌面操作系统.本方案采用海光CPU的服务器,运行DoraCloud云桌面系统.可以支持统信UOS桌面系统和麒麟桌面操作系统. 环境准备 服务器:海光 5 ...

  9. 错误解决:ElasticSearch SearchResponse的Hits[]总是比totalHits少一条记录

    在做ElasticSearch查询操作的时候,发现Hits[].length总是比totalHits.value少1.代码如下: SearchRequest request = new SearchR ...

  10. K8S部署之VMWare网络拓扑踩坑

    目录 背景 VMWare 虚拟网络 安装 Ubuntu Server 20.04 时遇到的网络问题 解决方法和解释 总结 背景 知乎上最近发现一篇好文 图解K8S(01):基于Ubuntu 20.04 ...