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 secondsAverage 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?
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:
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.