gpt4 book ai didi

android - HttpURLConnection.getInputStream 很慢

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:10 25 4
gpt4 key购买 nike

与使用相同服务器端服务的 iPhone 应用程序相比,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 seconds

Average time for writing response is less than 2 mil seconds.

知道为什么输入流会花费很多时间导致整个服务非常慢吗?

最佳答案

您没有衡量您认为正在衡量的东西。在您调用 getInputStream() 或 getResponseCode() 之前,不会向服务器写入任何内容。所以你真的在测量:

  • 连接时间
  • 传输时间
  • 服务器处理时间

当您认为自己只是在测量 getInputStream() 时间时。

原因是 HttpURLConnection 通过缓冲所有输出自动设置内容长度 header 。您可以通过使用分块传输模式来避免这种情况。然后至少你会看到时间真正流向了哪里。

关于android - HttpURLConnection.getInputStream 很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17439802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com