用Java发出同时的Web请求 [英] Make simultaneous web requests in Java

查看:116
本文介绍了用Java发出同时的Web请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指出我进行并行Web请求的代码段吗?我需要发出6个Web请求并连接HTML结果.

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?

谢谢.

推荐答案

使用 Callable<InputStream> .

开球示例:

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();

使用

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();
    }

}

另请参见:

  • Java教程:并发
  • See also:

    • Java tutorial: Concurrency
    • 这篇关于用Java发出同时的Web请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆