Looks like you’re using the Apache Http Components, and the api already provides the module Httpasyncclient for asynchronous requests.
pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.3</version>
</dependency>
Following more or less the same line as its implementation:
public class HttpUtils {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final CloseableHttpAsyncClient HTTP_CLIENT = HttpAsyncClients.createDefault();
static {
HTTP_CLIENT.start();
}
public static void post(String url, Object body, FutureCallback<HttpResponse> callback) throws IOException {
StringEntity json = new StringEntity(MAPPER.writeValueAsString(body), "UTF-8");
HttpPost post = new HttpPost(url);
post.setEntity(json);
HTTP_CLIENT.execute(post, callback);
}
public static void shutdown() throws IOException {
HTTP_CLIENT.close();
}
}
Testing with Jsonplaceholder:
public static void main(String[] args) throws IOException, InterruptedException {
BlogPost post = new BlogPost();
post.setId(1);
post.setUserId(1);
post.setTitle("Async Request");
post.setBody("This is an async post request");
FutureCallback<HttpResponse> callback = new FutureCallback<HttpResponse>() {
@Override
public void failed(Exception e) {
e.printStackTrace(System.out);
}
@Override
public void completed(HttpResponse response) {
try {
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (ParseException | IOException e) {
e.printStackTrace();
}
}
@Override
public void cancelled() {
System.out.println("cancelled");
}
};
HttpUtils.post("https://jsonplaceholder.typicode.com/posts", post, callback);
Thread.sleep(5000); // (teste) - aguarda resposta antes de finalizar
HttpUtils.shutdown();
}