将代理添加到Java中的HttpRequest。

huangapple go评论70阅读模式
英文:

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(&quot;https://myurl&quot;))
            .timeout(Duration.ofMinutes(2))
            .setHeader(&quot;User-Agent&quot;,&quot;Just an user agent&quot;)
            .GET()
            .build();

    HttpResponse&lt;String&gt; 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(&quot;proxy&quot;,port))))
        .build();

   //The request code is identical to what I wrote above.

The method is newBuilder anyway and not Builder.

huangapple
  • 本文由 发表于 2020年9月14日 03:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63874957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定