Make concurrent web requests in Java

Can someone point me to a snippet for creating concurrent web requests? I need to make 6 web requests and combine the HTML result.

Is there a quick way to accomplish this or do I need to go downstream?

Thank.

+3
source share
2 answers

Use ExecutorServicewith Callable<InputStream>.

Kickoff example:

ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Future<InputStream> response1 = executor.submit(new Request("http://google.com"));
Future<InputStream> response2 = executor.submit(new Request("http://stackoverflow.com"));
// ...
ByteArrayOutputStream totalResponse = new ByteArrayOutputStream();
copyAndCloseInput(response1.get(), totalResponse);
copyAndCloseInput(response2.get(), totalResponse);
// ...
executor.shutdown();

with

public class Request implements Callable<InputStream> {

    private String url;

    public Request(String url) {
        this.url = url;
    }

    @Override
    public InputStream call() throws Exception {
        return new URL(url).openStream();
    }

}

See also:

+4
source

I would advise finding out about java.util.concurrent.ExecutorService . It allows you to run tasks at the same time and will work well for the scenario you are describing.

+1
source

Source: https://habr.com/ru/post/1781943/


All Articles