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 Core中利用HttpClient通过配置代理(Proxy)进行HTTP GET和POST请求。首先,创建WebProxy对象并从appsettings.json获取代理URI,然后在HttpClientHandler中设置该代理。接着,利用HttpClient发送GET请求到指定URL,再发送带有参数的POST请求。配置文件包含了REST服务的基地址和代理服务器的URI。

241

被折叠的 条评论
为什么被折叠?



