c# Net Core设置代理(使用自定义Proxy 模式)get post调用接口

Net Core设置代理

有时候我们需要使用代理去调用某些外部接口,浏览器的代理IIS 读取不到,所以只能项目里面指定代理

  1. 通过在Startup.cs 文件配置HttpClient
 services.AddHttpClient("configured-inner-handler")
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler()
                {
                   // AllowAutoRedirect = false,
                   // UseDefaultCredentials = true,
                    Proxy = new WebProxy(Configuration["Proxy"]),
                    UseProxy = true
                };
            });

2.调用刚刚配置的HttpClient

 private readonly HttpClient client;
 public BaseCoreService(IConfiguration configuration, IHttpClientFactory IHttpClientFactory,ILogger<BaseCoreService> logger) {
            client = IHttpClientFactory.CreateClient("configured-inner-handler");
        }
    var request = new HttpRequestMessage(HttpMethod.Get, "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + $@"{appid}&secret={secret}&js_code={code.Trim()}");
     HttpResponseMessage response = await client.SendAsync(request);
                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 中使用 `HttpGet` 调用生成动态 IP 代理可以使用 Apache HttpClient 库实现。以下是一个简单的示例代码: ```java import java.io.IOException; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.DefaultProxyRoutePlanner; public class DynamicProxyExample { public static void main(String[] args) throws Exception { // 设置代理 IP 和端口号 String proxyAddress = "127.0.0.1"; int proxyPort = 1080; // 创建 HttpClient 对象,并设置代理 HttpHost proxy = new HttpHost(proxyAddress, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); CloseableHttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).build(); // 创建 HttpGet 对象 HttpGet httpGet = new HttpGet("http://www.example.com"); // 发送 HTTP 请求并读取响应 try { httpClient.execute(httpGet); // 输出响应内容 System.out.println(httpGet.toString()); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭 HttpClient HttpClientUtils.closeQuietly(httpClient); } } } ``` 在上面的示例代码中,我们使用 `HttpHost` 创建代理对象,然后使用 `DefaultProxyRoutePlanner` 创建代理路由计划器,并将其传递给 `HttpClientBuilder` 的 `setRoutePlanner` 方法中。在创建 `HttpGet` 对象时,将代理对象传递给 `HttpGet` 构造函数即可。接下来,发送 HTTP 请求并读取响应。最后,关闭 `HttpClient` 对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值