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

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

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"

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值