【问题标题】:Upgrading Java 9 HttpClient code to Java 11: BodyProcessor and asString()将 Java 9 HttpClient 代码升级到 Java 11:BodyProcessor 和 asString()
【发布时间】:2019-09-17 08:54:52
【问题描述】:

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】:

    看起来您需要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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2020-03-09
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多