问题描述

写代码的过程中,时常遇见要通过代码请求其他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. 感受 Vue3 的魔法力量

    ​ 作者:京东科技 牛至伟 近半年有幸参与了一个创新项目,由于没有任何历史包袱,所以选择了Vue3技术栈,总体来说感受如下: • setup语法糖<script setup lang=" ...

  2. css3写一个加载动画

    先制作一个正方形,让圆点在正方形的最外侧 <style> body { margin: 0; } .loading { width: 200px; height: 200px; backg ...

  3. vue 进阶学习(二):node.js、npm、webpack、vue-cli

    node.js.npm.webpack.vue-cli 前言:主要对插件的描述,安装,卸载.使用以及注意点 1 node.js 说明:是一个基于 Chrome V8 引擎的 JavaScript 运行 ...

  4. NLP领域任务如何选择合适预训练模型以及选择合适的方案【规范建议】【ERNIE模型首选】

    1.常见NLP任务 信息抽取:从给定文本中抽取重要的信息,比如时间.地点.人物.事件.原因.结果.数字.日期.货币.专有名词等等.通俗说来,就是要了解谁在什么时候.什么原因.对谁.做了什么事.有什么结 ...

  5. 3.3 DLL注入:突破会话0强力注入

    Session是Windows系统的一个安全特性,该特性引入了针对用户体验提高的安全机制,即拆分Session 0和用户会话,这种拆分Session 0和Session 1的机制对于提高安全性非常有用 ...

  6. Advanced Installer傻瓜式打包教程

    工具 Advanced Installer 11.0 前言 这个包不复杂,没有服务和注册表等操作,但需要.NET Framework 4.5和MySQL,同时需要初始化一下数据库,下面一起来实操一下. ...

  7. VB6的OfficeMenu控件 - 开源研究系列文章

    这次将原来VB6中喜欢和使用到的OfficeMenu的控件做一个使用介绍. 上次介绍了VB6中的控件引擎,但是那个只针对基本的控件,这个OfficeMenu控件在当时是收费的,笔者找度娘好不容易才下载 ...

  8. C#/.NET/.NET Core优秀项目和框架2024年1月简报

    前言 公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍.功能特点.使用方式以及部分功能截图 ...

  9. 深入剖析Java中的反射,由浅入深,层层剥离!

    写在开头 之前更新了不少Java的基础知识,比如Java的类.对象.基础类型.关键字.序列化.泛型.值传递等等,今天要上点深度了,来聊一聊Java中的 反射 ! 所谓反射,就是在运行时分析.检查和操作 ...

  10. KB0004.如何进行DoraCloud版本升级?

    升级过程为: 1).现有版本,进入维护模式,导出系统数据.    2).记录现当前版本DoraCloud VM 的IP地址,子网掩码.网关.DNS信息,将VM关机. 3).安装新版本DoraCloud ...