Javascript Fetch API equivalent in Java for Http requests?

Viewed 2582

I am currently learning about Threads in Java. I wanted to know what the standard protocol would be when making Http Requests in Java that would be similar to the code I have below, which uses Javascript Fetch API and asynchronous programming. For example, if I was using the Fetch API in Javascript to first make a GET request to grab some data from a REST endpoint that I would later use to make a POST request (as seen in the code below), I would need to use a Callback function or Promise (like below) to wait until that first request has retrieved its data for the second request to then proceed. Obviously, if I did not use Promises or nest the second Http POST in the first Fetch method (GET) below, and wrote two separate Fetch API calls (one for GET, one for POST, sequentially one after other aka top-to-bottom), both calls would "fire-off" simultaneously and the second POST request wouldn't have the data it needs to make a successful POST.

const myHttpGETandPOSTmethod = () => {

    // First Http request goes here

    fetch('http://example.com/movies.json', {
            method: 'GET',
            headers: // Some headers here,
        })
        .then(response => response.json())
        .then(data => {
                console.log(data))

            // Nest the second Http request inside here. It only runs after 1st request completes

            return fetch('http://example.com/movies.json', {
                    method: 'POST',
                    headers: // Some headers here,
                        body: JSON.stringify(body);
                })
                .then((response) => response.json())
                .then((data) => {
                    console.log('Success:', data);
                })
                .catch((error) => {
                    console.error('Error:', error);
                });
        })
}

So then, if I were using something like the Apache HttpClient https://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html library in Java, would the standard procedure be to "spin-up" another Thread (besides the main thread) to execute the GET request and then do a thread.join() such that after the first thread completes, then the second request can fire-off its own Thread?

Would I need to use a Callable instead of Runnable so that I can save the HttpEntity data response of the first GET request?

I guess I'm just trying to understand the best way to implement the scenario I posed above regarding an HTTP GET request that is needed to make a subsequent POST request, while both fires asynchronously such that they do not block the main thread.

You can make a basic GET request using the apache Http Library as such (POST is also very similar):

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);

try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();

    // Save the response body to a string
    String body = EntityUtils.toString(entity1, StandardCharsets.UTF_8);
    System.out.println(body);

    EntityUtils.consume(entity1);
} finally {
    response1.close();
}

Or am I on the wrong approach here and looking at this incorrectly? I believe the Http library in Apache offers both synchronous and asynchronous Http calls? or should I be using a newer library for Http in Java?

0 Answers
Related