-3

我有一个代码库(显然)可以Java 9Java 11. 它使用jdk.incubator.httpclientAPI 并根据答案更改模块信息在大多数情况下有效,但不仅仅是包已更改。

我仍然无法修复的代码如下:

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);
}

编译错误是:

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

如何将代码转换为等效Java 11版本?

4

1 回答 1

10

看起来您需要HttpResponse.BodyHandlers.ofString()作为. (旧的 Java 9 文档,在这里。)HttpResponse.BodyHandler.asString()HttpRequest.BodyPublishers.ofString(String)HttpRequest.BodyProcessor.fromString(String)

你的代码看起来像

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);
}
于 2019-04-28T14:50:10.163 回答