2

简单的问题:

是否可以同时请求多个 httpURLConnection?我正在创建一个工具来检查某些服务器上是否存在页面,目前,Java 似乎要等到每个 httpURLConnection 完成才能启动一个新的。这是我的代码:

public static String GetSource(String url){
String results = "";
try{
  URL SourceCode = new URL(url);
  URLConnection connect = SourceCode.openConnection();
  connect.setRequestProperty("Host", "www.someserver.com");
  connect.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko/20100101 Firefox/11.0");
  connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  connect.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  connect.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  connect.setRequestProperty("Keep-Alive", "115");
  connect.setRequestProperty("Connection", "keep-alive");
  BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream(), "UTF-8"));
  String inputLine;
  while ((inputLine = in.readLine()) != null){
    results += inputLine;
  }
  return results;
}catch(Exception e){
  // Something's wrong
}
return results;
}

非常感谢!

4

2 回答 2

1

是的,您发布的代码可以同时从多个线程调用。

于 2012-04-18T17:27:19.683 回答
1

您需要为每个命中创建一个线程。创建一个实现 Runnable 的类,然后将所有连接代码放入 run 方法中。

然后用这样的东西运行它......

for(int i=0; i < *thread count*; i++){
    Thread currentThread = new Thread(*Instance of your runnable Class*);
    currentThread.start();
}
于 2012-04-18T17:48:14.803 回答