Avatar of Rohit Bajaj
Rohit Bajaj
Flag for India

asked on 

Refactoring a java code and correct use of Futures

Currently in my java code i am having the following class :
This is just an asynchronous way to make  HTTP post request with a json string.
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.util.concurrent.Future;

public class WebHookAdapter {
    private static Unirest unirest = new Unirest();
    static String webhookEndpoint;

    public static void main(String[] args) {
        Future<HttpResponse<JsonNode>> future = send("ldjflksdfj");


    public static Future send(String text) {
        String json = "{\"text\" : \"" + text + "\"}";
        Future<HttpResponse<JsonNode>> future;

        future = unirest.post(webhookEndpoint).header("Content-Type", "application/json").body(json).asJsonAsync(new Callback<JsonNode>() {
            public void completed(HttpResponse<JsonNode> httpResponse) {


            public void failed(UnirestException e) {


            public void cancelled() {

        return future;

Open in new window

Here i am using unirest for java to just make an http post call.

To make the http calls non blocking i used the Future version.
Now in the main method i am using :        Future<HttpResponse<JsonNode>> future = send("ldjflksdfj");

what do i do with this future.
If i use future.get()... i read it blocks...
In the case where i will be doing multiple http post request asynchoronously.
Is this a correct approach ??

Also the new CallBack<...code can i move it out of the method. Whats the general practice.
Is this the way to use it. Can you suggest a better approach to this problem (Making multiple asycn http post request)


Avatar of undefined
Last Comment

8/22/2022 - Mon