0

Trying to make a get request in Java 17 using HttpClient. All documentation I find tells me I should be able to do:

HttpClient client = HttpClient.newHttpClient();
URI uri = new URI("https://postman-echo.com/get");
HttpRequest request = HttpRequest.newBuilder(uri);

However, I get an error

XmlTools.java:44: error: incompatible types: Builder cannot be converted to HttpRequest
        HttpRequest request = HttpRequest.newBuilder(uri);
                                                    ^

If I change the last line to

Builder request = HttpRequest.newBuilder(uri);

then this error disappears, but the next part fails

try {
    HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
}
XmlTools.java:50: error: incompatible types: Builder cannot be converted to HttpRequest
            HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
                                                             ^

Verbose compile gives me

XmlTools.java:50: error: method send in class HttpClient cannot be applied to given types;
            HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
                                                       ^
  required: HttpRequest,BodyHandler<T>
  found:    Builder,BodyHandler<InputStream>
  reason: cannot infer type-variable(s) T
    (argument mismatch; Builder cannot be converted to HttpRequest)
  where T is a type-variable:
    T extends Object declared in method <T>send(HttpRequest,BodyHandler<T>)
1 error

One other thing I noticed, not sure if related, is that I'm unable to stack methods like so:

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .headers("key1", "value1", "key2", "value2")
  .GET()
  .build();

Am I in a wrong environment? I'm using OpenJDK on Windows.

Edit: Yea, it was user error. I should've copy/pasted instead of trying to pick out what I need. Thanks for your time.

  • 3
    "All documentation I find tells me I should be able to do" - could you point to *any* documentation that actually suggests you should be able to do that? I wouldn't expect you to be able to - I'd expect you to have to call `build()` at the end, and that all documentation would show that. (Additionally you say that you're "unable to stack methods" but you haven't told us what happens when you try.) – Jon Skeet Oct 14 '21 at 05:42

1 Answers1

4

HttpRequest.newBuilder(uri) returns an HttpRequest.Builder. You have to call .build method to create the actual HttpRequest instance:

HttpRequest request = HttpRequest.newBuilder(uri).build();

You could learn about the Builder design pattern here.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35