本文主要介绍.NET Core中,使用HttpClient执行GET和POST请求配置代理(Proxy)的方法及示例代码。

1、配置Proxy及执行GET和POST请求的代码

using System.Net;
using System.Net.Http;
var builder = new ConfigurationBuilder()
	 .SetBasePath(Directory.GetCurrentDirectory())
	 .AddJsonFile("appsettings.json");
var configuration = builder.Build();
var webProxy = new WebProxy(
	 new Uri(configuration["ProxyUri"]), 
	 BypassOnLocal: false);
var proxyHttpClientHandler = new HttpClientHandler {
	 Proxy = webProxy,
	 UseProxy = true,
};
var client = new HttpClient(proxyHttpClientHandler) {
	 BaseAddress = new Uri(configuration["RestServiceUri"])
};
//发送Get请求
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
//发送Post请求
var values = new Dictionary
{
   { "thing1", "hello" },
   { "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

2、配置文件

/* appsettings.json */
{
"RestServiceUri": "http://192.168.31.11:5001/api",
"ProxyUri": "http://192.168.31.11:8080"
}

相关文档.Net(C#)后台发送Get和Post请求的几种方法总结

推荐文档