与使用相同服务器端服务的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。
该过程的平均时间如下:
发布到服务器的平均时间不到2毫秒 创建输入流的平均时间大约需要5秒
写入响应的平均时间小于2毫秒。
有什么想法为什么输入流需要很长时间才能使整个服务变得非常慢?
你没有衡量你认为自己在测量什么。在调用getInputStream()或getResponseCode()之前,不会将任何内容写入服务器。所以你真的在测量:
当你认为你只是在测量getInputStream()时。
原因是HttpURLConnection通过缓冲所有输出来自动设置内容长度标头。您可以通过使用分块传输模式来避免这种情况。那么至少你会看到时间的真正去向。
将urlConnection.setConnectTimeout()设置为较低的超时。
URLConnection.setConnectTimeout()的类文档说:
设置连接时等待的最长时间(以毫秒为单位)。如果在建立连接之前超时,则连接到服务器将失败并出现SocketTimeoutException。默认值0使我们进行阻塞连接。这并不意味着我们永远不会超时,但这可能意味着您将在几分钟后获得TCP超时。
警告:如果主机名解析为多个IP地址,则此客户端将按RFC 3484顺序尝试每个IP地址。如果连接到这些地址中的每一个都失败,则在连接尝试引发异常之前将经过多次超时。支持IPv6和IPv4的主机名始终至少有2个IP地址。
我最初将我的设置为urlConnection.setConnectTimeout(30000);
然后将其更改为urlConnection.setConnectTimeout(1000)
。我立刻看到了更快的结果。
希望这可以帮助!
这可能与JDK 7中引入的错误有关。“使用keep-alive缓存时,HttpServer会导致1000毫秒的延迟”。看到:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8009548
根据您的目的,建议的解决方法是多线程HttpUrlConnection。例如,如果您正在使用HttpServer,则可以执行以下操作:
server.setExecutor( Executors.newFixedThreadPool( 5 ) );