I am making an HTTP get request to a website for an android application I am making.
I am using a DefaultHttpClient and using HttpGet to issue the request. I get the entity response and from this obtain an InputStream object for getting the html of the page.
I then cycle through the reply doing as follows:
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String x = "";
x = r.readLine();
String total = "";
while(x!= null){
total += x;
x = r.readLine();
}
However this is horrendously slow.
Is this inefficient? I'm not loading a big web page - www.cokezone.co.uk so the file size is not big. Is there a better way to do this?
Thanks
Andy
The problem in your code is that it's creating lots of heavy
String
objects, copying their contents and performing operations on them. Instead, you should useStringBuilder
to avoid creating newString
objects on each append and to avoid copying the char arrays. The implementation for your case would be something like this:You can now use
total
without converting it toString
, but if you need the result as aString
, simply add:String result = total.toString();
I'll try to explain it better...
a += b
(ora = a + b
), wherea
andb
are Strings, copies the contents of botha
andb
to a new object (note that you are also copyinga
, which contains the accumulatedString
), and you are doing those copies on each iteration.a.append(b)
, wherea
is aStringBuilder
, directly appendsb
contents toa
, so you don't copy the accumulated string at each iteration.If the file is long, you can optimize your code by appending to a StringBuilder instead of using a String concatenation for each line.
I am use to read full data:
To convert the InputStream to String we use the BufferedReader.readLine() method. We iterate until the BufferedReader return null which means there's no more data to read. Each line will appended to a StringBuilder and returned as String.
And finally from any class where you want to convert call the function
complete
Have you tried the built in method to convert a stream to a string? It's part of the Apache Commons library (org.apache.commons.io.IOUtils).
Then your code would be this one line:
The documentation for it can be found here: http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29
The Apache Commons IO library can be downloaded from here: http://commons.apache.org/io/download_io.cgi