HttpURLConnection.getInputStream very slow

Timson picture Timson · Jul 3, 2013 · Viewed 8.4k times · Source

HttpURLConnection.getInputStream takes very much time when compared to iPhone App which uses the same server side services.

The following code is used for the service :

         date= new java.util.Date();             
         Log.d("time","Time Stamp before posting  "+new Timestamp(date.getTime()));

         URL ur= new URL(url);           
         HttpURLConnection conn = (HttpURLConnection) ur.openConnection();
         conn.setRequestProperty("Connection", "close");
         conn.setReadTimeout(10000);
         conn.setConnectTimeout(15000);
         conn.setRequestMethod("POST");
         conn.setDoInput(true);
         conn.setDoOutput(true);             
         OutputStream os = conn.getOutputStream();
         BufferedWriter writer = new BufferedWriter(
                 new OutputStreamWriter(os, "UTF-8"));
         writer.write(getQuery(nameValuePairs));
         writer.close();
         os.close();
         conn.connect();

         StringBuffer response=null;             
         try{           
             Log.d("time","Time Stamp bfr InputStream  "+new Timestamp(date.getTime()));    

             InputStream is = conn.getInputStream();

             date= new java.util.Date();             
             Log.d("time","Time Stamp aftr InputStream  "+new Timestamp(date.getTime()));            

             BufferedReader rd = new BufferedReader(new InputStreamReader(is));
             String line;
             response = new StringBuffer(); 
             while((line = rd.readLine()) != null) {
                 response.append(line);
                 response.append('\r');
             }
             rd.close();
             response.toString();
             result=response.toString();

         } catch (Exception e) {

        }

To check where the service takes time, I put the log entries to print TimeStamp.

The average time for the process is as follows :

Average time for posting to server takes less than 2 Mil seconds
Average time for creating input stream takes almost 5 seconds

Average time for writing response is less than 2 mil seconds.

Any idea on why the input stream takes much time which makes the entire service very slow?

Answer

user207421 picture user207421 · Oct 11, 2014

You're not measuring what you think you're measuring. Nothing gets written to the server until you call getInputStream() or getResponseCode(). So you're really measuring:

  • connection time
  • transmission time
  • processing time at the server

when you think you're just measuring getInputStream() time.

The reason is that HttpURLConnection auto-sets the content-length header, by buffering all the output. You can avoid that by using chunked transfer mode. Then at least you will see where the time is really going.