英文:
Add Proxy to HttpRequest in java
问题
以下是翻译好的部分:
我正在尝试理解如何在使用Java API时为每个请求实现类似以下代码的代理:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.create("https://myurl"))
.timeout(Duration.ofMinutes(2))
.setHeader("User-Agent","Just an user agent")
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
我从文档中看到(https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html#Asynchronous%20Example)
可以在“同步”请求中实现。我的代码位于一个方法中,将在多个线程中并行运行。那么如何在“异步请求”中设置代理?如果不可能的话,它们之间有什么区别?
英文:
I'm trying to understand how can I implement the use of a proxy for each request built like the following using Java API:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2)
.uri(URI.createh("https://myurl"))
.timeout(Duration.ofMinutes(2))
.setHeader("User-Agent","Just an user agent")
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
I'm seeing from the doc (https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html#Asynchronous%20Example)
that is possible with Synchronous
requests. My code is within a method and it will run with threads parallelly. So how is it possible to set a proxy with Asynchronous Requests
? If it is not possible, what's the difference between them?
答案1
得分: 5
解决了,关于这一点文档不太清楚,但最终我能够在构建客户端时设置代理:
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress("proxy", port)))
.build();
// 请求代码与我上面写的完全相同。
该方法是 newBuilder
,而不是 Builder
。
英文:
Solved, it's a bit unclear the doc about that but at the end, I was able to set the proxy when building the client:
HttpClient client = HttpClient.newBuilder().
proxy(ProxySelector.of(new InetSocketAddress("proxy",port))))
.build();
//The request code is identical to what I wrote above.
The method is newBuilder
anyway and not Builder
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论