Search code examples
javajsonjava-9java-11java-http-client

Upgrading Java 9 HttpClient code to Java 11: BodyProcessor and asString()


I have a code base which (apparently) works under Java 9 but does not compile under Java 11. It uses the jdk.incubator.httpclient API and changing the module information according to this answer works for the most part but more than the package has changed.

The code I still have trouble fixing is the following:

private static JSONObject sendRequest(JSONObject json) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest httpRequest = HttpRequest.newBuilder(new URI(BASE_URL))
            .header("Accept", "application/json")
            .header("Content-Type", "application/json")
            .timeout(TIMEOUT_DURATION)
            .POST(HttpRequest.BodyProcessor.fromString(json.toString()))
            .build();

    HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandler.asString());
    String jsonResponse = httpResponse.body();

    return new JSONObject(jsonResponse);
}

The compilation errors are:

Error:(205, 94) java: cannot find symbol
  symbol:   method asString()
  location: interface java.net.http.HttpResponse.BodyHandler
Error:(202, 34) java: cannot find symbol
  symbol:   variable BodyProcessor
  location: class java.net.http.HttpRequest

How can I transform the code into an equivalent Java 11 version?


Solution

  • Looks like you need HttpResponse.BodyHandlers.ofString() as a replacement for HttpResponse.BodyHandler.asString() and HttpRequest.BodyPublishers.ofString(String) as a replacement for HttpRequest.BodyProcessor.fromString(String). (Old Java 9 docs, here.)

    Your code would then look like

    private static JSONObject sendRequest(JSONObject json) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(BASE_URL))
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .timeout(TIMEOUT_DURATION)
                .POST(HttpRequest.BodyPublishers.ofString(json.toString()))
                .build();
    
        HttpResponse<String> httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        String jsonResponse = httpResponse.body();
    
        return new JSONObject(jsonResponse);
    }