将Java 9 HttpClient代码升级到Java 11:BodyProcessor和asString()

问题描述 投票:-4回答:1

I have a code base(显然)在Java 9下工作,但不在Java 11下编译。它使用jdk.incubator.httpclient API并根据this更改模块信息回答大部分工作,但超过包更改。

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

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版本?

java json java-9 java-11 java-http-client
1个回答
4
投票

看起来你需要HttpResponse.BodyHandlers.ofString()作为HttpResponse.BodyHandler.asString()HttpRequest.BodyPublishers.ofString(String)的替代品来替代HttpRequest.BodyProcessor.fromString(String)。 (旧Java 9文档,here。)

您的代码看起来就像

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.