Search code examples
javaresthttpwebsocketjava-http-client

How can I prevent java.net.http.HttpClient from making an upgrade request?


Upon making a call from a Java project to a Python rest API, I am met with an error that states "Unsupported upgrade request."

I'm making a simple GET request from Java, to the endpoint written in Python, and at some point Java decides it wants to request to upgrade the connection to a websocket. My issue is, I never reference websockets in my Java project whatsoever, and when I debug and look at the value of headers in the request, it does not show any headers at all, but at some point before it hits the network it decides it wants to do an upgrade request. I haven't sniffed my own traffic to confirm the existence of the header yet; but the problem does not exist when I use OKHTTP instead of java.net.http.HttpClient

This code results in the Unsupported Upgrade Request error returned by the Python API.

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("http://127.0.0.1:8000/"))
    .method("GET", HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

This code works just fine

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("http://127.0.0.1:8000/")
  .get()
  .build();

Response response = client.newCall(request).execute();

Is anyone familiar with disabling the upgrade request in the native HTTP client java provides?


Solution

  • Requests shouldn't be upgraded to websocket - but the default for the HttpClient is to request an upgrade to HTTP/2.

    If you don't want the HttpClient to request an upgrade to HTTP/2 you can set the version in the request to Version.HTTP_1_1, or set the default version in the HttpClient to Version.HTTP_1_1.

    See: HttpRequest.Builder::version or HttpClient.Builder::version