logoalt Hacker News

ffsm8today at 11:31 AM2 repliesview on HN

Ahh, java. You never change, even if you're modern

    HttpClient client = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .followRedirects(Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(20))
        .proxy(ProxySelector.of(
           new InetSocketAddress("proxy.example.com", 80)
        ))
        .authenticator(Authenticator.getDefault())
        .build();

       HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

       System.out.println(response.statusCode());
       System.out.println(response.body());
For the record, you're most likely not even interacting with that API directly if you're using any current framework, because most just provide automagically generated clients and you only define the interface with some annotations

Replies

awkwardpotatotoday at 12:19 PM

What's the matter with this? It's a clean builder pattern, the response is returned directly from send. I've certainly seen uglier Java

show 4 replies
lenkitetoday at 1:04 PM

Your http client setup is over-complicated. You certainly don't need `.proxy` if you are not using a proxy or if you are using the system default proxy, nor do you need `.authenticator` if you are not doing HTTP authentication. Nor do you need `version` since there is already a fallback to HTTP/1.1.

  HttpClient client = HttpClient.newBuilder()
    .followRedirects(Redirect.NORMAL)
    .connectTimeout(Duration.ofSeconds(20))
    .build();
show 1 reply