I have an application with a lot of java in which I have to send HTTP messages to another server. I am currently using the org.apache.commons.httpclient library:
private static void sendData(String data) { HttpClient httpclient = new HttpClient(); StringRequestEntity requestEntity; try { requestEntity = new StringRequestEntity(data, "application/json", "UTF-8"); String address = "http://<my host>/events/" PostMethod postMethod = new PostMethod(address); postMethod.setRequestEntity(requestEntity); httpclient.executeMethod(postMethod); } catch (Exception e) { LOG.error("Failed to send data ", e); } }
This means that I send my HTTP requests synchronously, which is not suitable for my multi-threaded application with a large volume. Therefore, I would like to change these calls to asynchronous non-blocking HTTP calls.
I looked through a few options, such as apache async client and xsocket , but could not get it to work.
Tried ning :
private static void sendEventToGrpahiteAsync(String event) { LOG.info("\n" + "sendEventToGrpahiteAsync"); try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) { BoundRequestBuilder post = asyncHttpClient.preparePost(); post.addHeader("Content-Type", "application/json"); post.setBodyEncoding("UTF-8"); post.setBody(event); post.execute(new HttpRequestCompletionHandler()); } catch (Exception e) { LOG.error("Failed to sending event", e); } }
I tried Apache HttpAsyncClient :
private static void sendEventToGrpahiteAsync(String event) { LOG.info("\n" + "sendEventToGrpahiteAsync"); try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) { httpclient.start(); HttpPost request = new HttpPost(addr); StringEntity entity = new StringEntity(event, ContentType.create("application/json", Consts.UTF_8)); request.setEntity(entity); httpclient.execute(request, null); } catch (Exception e) { LOG.error("Failed to sending event", e); } }
I tried xsocket :
private static void sendEventToGrpahiteAsync2(String event) { LOG.info("\n" + "sendEventToGrpahiteAsync"); try (INonBlockingConnection con = new NonBlockingConnection(<SERVER_IP>, 80); IHttpClientEndpoint httpClientConnection = new HttpClientConnection(con)) { IHttpResponseHandler responseHandler = new MyResponseHandler(); IHttpRequest request = new PostRequest(url_address, "application/json", Consts.UTF_8.toString(), event); request.setTransferEncoding(Consts.UTF_8.toString()); httpClientConnection.send(request, responseHandler); } catch (Exception e) { LOG.error("Failed to sending event", e); } }
I get no exceptions, but the message also misses the target. To be clear, the goal is the graphics server therefore, as soon as the message arrives, it is clearly visible on the chart. Synchronous messages work well, I see the result on the graph, but none of the asynchronous messages appear on my destination graph.
What am I missing?
thanks