与使用相同服务器端服务的 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) {
}
为了检查服务需要时间的地方,我将日志条目打印到时间戳。
该过程的平均时间如下:
发布到服务器的平均时间不到 2 百万秒
创建输入流的平均时间几乎是 5 秒写入响应的平均时间小于 2 百万秒。
关于为什么输入流需要很多时间导致整个服务非常慢的任何想法?