-2

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?

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185

1 Answers1

11

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);
}
Savior
  • 3,225
  • 4
  • 24
  • 48