Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make simultaneous web requests in Java

Could someone point me to snippet for making parallel web-requests? I need to make 6 web requests and concatenate the HTML result.

Is there a quick way to accomplish this or do i have to go the threading way?

Thank you.

like image 393
Mridang Agarwalla Avatar asked Oct 15 '25 10:10

Mridang Agarwalla


2 Answers

Use ExecutorService with 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:

  • Java tutorial: Concurrency
like image 78
BalusC Avatar answered Oct 17 '25 01:10

BalusC


I'd recommend learning about java.util.concurrent.ExecutorService. It allows you to run tasks simultaneously and would work well for the scenario you describe.

like image 41
laz Avatar answered Oct 17 '25 01:10

laz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!