在 java 中将代理添加到 HttpRequest
Add Proxy to HttpRequest in java
我正在尝试了解如何为使用 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());
我从文档中看到 (https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html#Asynchronous%20Example)
Synchronous
请求是可能的。我的代码在一个方法中,它将 运行 与线程并行。那么如何使用 Asynchronous Requests
设置代理呢?如果不可以,它们之间有什么区别?
已解决,关于这个的文档有点不清楚,但最后,我能够在构建客户端时设置代理:
HttpClient client = HttpClient.newBuilder().
proxy(ProxySelector.of(new InetSocketAddress("proxy",port))))
.build();
//The request code is identical to what I wrote above.
方法是 newBuilder
而不是 Builder
。
我正在尝试了解如何为使用 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());
我从文档中看到 (https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html#Asynchronous%20Example)
Synchronous
请求是可能的。我的代码在一个方法中,它将 运行 与线程并行。那么如何使用 Asynchronous Requests
设置代理呢?如果不可以,它们之间有什么区别?
已解决,关于这个的文档有点不清楚,但最后,我能够在构建客户端时设置代理:
HttpClient client = HttpClient.newBuilder().
proxy(ProxySelector.of(new InetSocketAddress("proxy",port))))
.build();
//The request code is identical to what I wrote above.
方法是 newBuilder
而不是 Builder
。