5

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?

Virgula
  • 318
  • 4
  • 12
  • 1
    The asynchronous example is using the same `HttpClient` from the synchronous example. You set the proxy when [building the client](https://docs.oracle.com/en/java/javase/14/docs/api/java.net.http/java/net/http/HttpClient.Builder.html#proxy(java.net.ProxySelector)). – Slaw Sep 13 '20 at 20:44
  • @Slaw no, if you try to add the proxy method to the chain, In my case, I `HttpClientC.Builder().proxy(...).newHttpClient()` but this seems not working. – Virgula Sep 14 '20 at 07:11
  • @Slaw solved as I posted, thank you. – Virgula Sep 14 '20 at 07:32

1 Answers1

5

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.

Virgula
  • 318
  • 4
  • 12
  • Note the "buildable" class having a method named something like `newBuilder` to create the builder is a relatively common occurrence in the builder pattern. Especially when the builder is an interface. – Slaw Sep 14 '20 at 18:04
  • @Slaw yeah but in your link there is a reference to a Builder method not to newBuilder – Virgula Sep 15 '20 at 10:08
  • Ah. My link was to the `HttpClient.Builder#proxy(ProxySelector)` method to show you exactly where you specify the proxy, since that's what you seemed most interested in. And note that `HttpClient.Builder` does not denote a method but a nested interface. – Slaw Sep 15 '20 at 17:46
  • @Slaw I didn’t watch carefully enough. Thank you – Virgula Sep 15 '20 at 21:38