3

I have a service listening in HTTP called by POST. Using software like curl, Postman, etc, the request is successful (status code 200).

I need to consume this service from Java. But using the native HttpClient from Java 11, I get a 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

Trying with the Apache HttpClient library, the call is successful:

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

Why it doesn't work with Java native HttpClient? What's the difference between the calls?

Johny
  • 809
  • 9
  • 19
  • the issue may not be with the library or the request per se, but with firewall, server connectivity, dns issues or web-server issue. Do any other requests using this Http Client to any other of your services are successful? – edward_wong Sep 09 '20 at 11:56
  • @edward_wong Yes, using the Java HttpClient to request other services does work ok. That's why I don't know what is the problem here, only this service fails and only with the Java HttpClient. – Johny Sep 09 '20 at 12:06
  • You could try to switch on logging `-Djdk.httpclient.HttpClient.log=headers,requests,errors` - that might reveal something... – daniel Sep 15 '20 at 12:29

0 Answers0