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"
}