4

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
  • How would you do it other than threads? If there's a framework that does it, it's going to use threads. – Falmarri Dec 24 '10 at 03:50

2 Answers2

7

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:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

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.

laz
  • 28,320
  • 5
  • 53
  • 50