2

我有一个通过 POST 调用的 HTTP 服务。使用curlPostman 等软件,请求成功(状态码 200)。

我需要从 Java 中使用此服务。但是使用HttpClientJava 11 的本机,我得到 504 Gateway Timeout ...

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().
    header("Content-Type", "application/json").
    uri(URI.create(service_url)).
    POST(HttpRequest.BodyPublishers.ofString(json_string)).build();
HttpResponse<String> res = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(res.statusCode()); // 504

尝试使用 Apache HttpClient 库,调用成功:

StringEntity requestEntity = new StringEntity(
    json_string, ContentType.APPLICATION_JSON);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(service_url);
httpPost.setEntity(requestEntity);
CloseableHttpResponse res = httpclient.execute(httpPost);
System.out.println(res.getStatusLine().getStatusCode()); //200

为什么它不适用于 Java native HttpClient?通话之间有什么区别?

4

0 回答 0