Diego Sagrera
Diego Sagrera

Reputation: 263

Java httpURLConnection threaded

Simple question:

Is it possible to request SEVERAL httpURLConnection at the same time? I'm creating a tool to check if pages exists on certain server, and at the moment, Java seems to wait until for each httpURLConnection finishes to start a new one. Here's my code:

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

Thanks a lot!

Upvotes: 2

Views: 5514

Answers (2)

Matt Klooster
Matt Klooster

Reputation: 767

You need to create a thread for each hit. Create a class that implements Runnable, then put all of your connection code inside the run method.

Then run it with something like this...

for(int i=0; i < *thread count*; i++){
    Thread currentThread = new Thread(*Instance of your runnable Class*);
    currentThread.start();
}

Upvotes: 1

Angelo Fuchs
Angelo Fuchs

Reputation: 9941

Yes it is possible, the code you posted can be called from multiple threads at the same time.

Upvotes: 1

Related Questions