将Java 9 HttpClient代码升级到Java 11:BodyProcessor和asString()
它显然可以在Java9下工作,但不能在Java11下编译。它使用jdk.incubator.httpclient API,并根据answer更改模块信息,这在很大程度上起作用,但超过了包的更改 我仍然无法修复的代码如下:将Java 9 HttpClient代码升级到Java 11:BodyProcessor和asString(),java,json,java-9,java-11,java-http-client,Java,Json,Java 9,Java 11,Java Http Client,它显然可以在Java9下工作,但不能在Java11下编译。它使用jdk.incubator.httpclient API,并根据answer更改模块信息,这在很大程度上起作用,但超过了包的更改 我仍然无法修复的代码如下: private static JSONObject sendRequest(JSONObject json) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpReque
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);
}
如何将代码转换为等效的Java 11版本?看起来您需要替换HttpResponse.BodyHandler.asString和HttpRequest.BodyProcessor.fromStringString。旧的Java9文档
您的代码将如下所示
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);
}
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);
}