Thursday, August 7, 2014

HTTP GET in Java, performance issues

My first version was:

import java.net.*;

URL url = new URL(theURL);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String wholeInput = "";
String inputLine = null;
while ((inputLine = in.readLine()) != null) 

{ wholeInput += inputLine; }



The above code proved to be EXTREMELY slow. The below version is MUCH faster:

URL url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String wholeInput = "";
String inputLine = null;
while ((inputLine = in.readLine()) != null) 
 { wholeInput += inputLine; }
in.close(); 


No comments: