【发布时间】:2011-10-13 20:38:20
【问题描述】:
我正在使用以下两个函数从服务器下载字符串。我还记录了下载文本所需的时间,无论是客户端看到的还是服务器看到的。下载的字符串永远不会一样。
服务器时间只有几毫秒,但客户端看到的时间平均为 100 毫秒,具体取决于 wifi 信号。即使服务器时间仍在可接受的范围内,客户端时间有时也会上升到 3000 毫秒(但从不超过 3200 毫秒)。
我开始认为超时是在某个地方定义的,但我不知道它可能在哪里。它不在我的代码中,我在开发者网站和谷歌上环顾四周没有结果。
我希望有人能给我一些线索来定义这个延迟,并确认它默认是 3000 毫秒。
private String DownloadText(String URL)
{
String str = "";
int BUFFER_SIZE = 2000;
InputStream in = null;
try{
in = OpenHttpConnection(URL);
} catch (IOException e1) {
e1.printStackTrace();
return "";
}
catch(ArithmeticException ae){
//
}
try{
InputStreamReader isr = new InputStreamReader(in);
int charRead;
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
与
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
顺便说一句:我从谷歌的一个搜索结果中借用了这两个功能。
编辑:我从一个线程中调用 DownloadText(url)。我开始认为这可能与超时有关。是吗?
【问题讨论】:
标签: android http download timeout