首页 .Net .NET Core 使用HttpClient通过配置Proxy(代理)执行Get和Post请求数据操作

.NET Core 使用HttpClient通过配置Proxy(代理)执行Get和Post请求数据操作

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请求的几种方法总结

特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。