Tuesday, April 28, 2009

Code to connect to a website

Following is the code i used to test an application .
I did not want the thread and also it did not want it to consume CPU.
I wanted it to use random network delay.

try {
long l=System.currentTimeMillis();
URL ourURL = new URL("http://www.nomsdom.blogspot.com");
HttpURLConnection huc = (HttpURLConnection)ourURL.openConnection();
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
huc.setRequestProperty("Pragma", "no-cache");
huc.connect();
BufferedReader reader = new BufferedReader(new
InputStreamReader(huc.getInputStream()));

String line = null;
while ((line = reader.readLine()) != null) {
}
System.out.println("Time taken "+((System.currentTimeMillis()-l)/1000)+"secs");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch(Exception e)
{
System.err.println("General Exception " + e);
e.printStackTrace();
}

Code taken from here

No comments: