How to make a POST REST call asynchronously in Java

Without knowing your requirements or expectations:

Here is a simple example without proper error handling which shows how an async HTTP call can be done using Java 8

public static void main(String ... args) throws InterruptedException, ExecutionException, TimeoutException {
    Future<Object> futureResult = getObjectAsync();

    Object value = futureResult.get(500, TimeUnit.MILLISECONDS);
}

public static Future<Object> getObjectAsync() {
    return CompletableFuture.supplyAsync(() -> doHttpCall());
}

static Object doHttpCall() {
    try {
        HttpURLConnection urlConnection = 
            (HttpURLConnection) new URL("http://example.net/something").openConnection();
            urlConnection.setRequestMethod("POST");
        try (OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream())) {
            out.write("params as json");
        }

        try (InputStreamReader in = new InputStreamReader(urlConnection.getInputStream())) {
            // convert to Object
            return new Object();
        }

    } catch (IOException e ) {
        throw new RuntimeException(e);
    }
}

Leave a Comment

tech