android – HttpURLConnection.getInputStream很慢
作者:互联网
与使用相同服务器端服务的iPhone App相比,HttpURLConnection.getInputStream需要很长时间.
以下代码用于服务:
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) {
}
要检查服务花费时间的位置,我将日志条目打印到TimeStamp.
该过程的平均时间如下:
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.
有什么想法为什么输入流需要很长时间才能使整个服务变得非常慢?
解决方法:
你没有衡量你认为自己在测量什么.在调用getInputStream()或getResponseCode()之前,不会将任何内容写入服务器.所以你真的在测量:
>连接时间
>传输时间
>在服务器上处理时间
当你认为你只是在测量getInputStream()时.
原因是HttpURLConnection通过缓冲所有输出来自动设置内容长度标头.您可以通过使用分块传输模式来避免这种情况.那么至少你会看到时间的真正去向.
标签:android,inputstream,httpurlconnection,androidhttpclient 来源: https://codeday.me/bug/20190709/1409183.html