Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpURLConnection.getInputStream very slow

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?

like image 375
Timson Avatar asked Jul 03 '13 04:07

Timson


1 Answers

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.

like image 54
user207421 Avatar answered Sep 24 '22 16:09

user207421