gpt4 book ai didi

java - Apache HttpClient 4.3.5 设置代理

转载 作者:搜寻专家 更新时间:2023-10-31 19:38:30 24 4
gpt4 key购买 nike

似乎我可以在构造新的 HttpClient 时指定代理:

HttpHost proxy = new HttpHost("someproxy", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();

取自http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

是否可以修改现有客户端的代理设置。

最佳答案

您可以创建自己的 HttpRoutePlanner 实现,以允许更改 HttpHost。

public class DynamicProxyRoutePlanner implements HttpRoutePlanner {

private DefaultProxyRoutePlanner defaultProxyRoutePlanner = null;

public DynamicProxyRoutePlanner(HttpHost host){
defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(host);
}

public void setProxy(HttpHost host){
defaultProxyRoutePlanner = new DefaultProxyRoutePlanner(host);
}

public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) {
return defaultProxyRoutePlanner.determineRoute(target,request,context);
}
}

然后你可以在你的代码中使用这个 DynamicProxyRoutePlanner

HttpHost proxy = new HttpHost("someproxy", 8080);
DynamicProxyRoutePlanner routePlanner = new DynamicProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();

//Any time change the proxy
routePlanner.setProxy(new HttpHost("someNewProxy", 9090));

关于java - Apache HttpClient 4.3.5 设置代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25567973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com