我最近在我的 Android 应用程序中重构了一些网络代码,以使用 Google 推荐的 HTTPUrlConnection 。以前,我使用的是 Apache 的 HTTPClient。我不确定这些事情是否相关。
我最近对网络代码所做的另一件事是使用 AsyncTask 进行调用。以前我只是在主线程上工作(显然很糟糕),因此我的应用程序在获取数据时似乎挂起。问题是,自从切换到 AsyncTask 以来,我经常遇到超时错误。
为什么我会收到此超时错误?
java.net.ConnectException: failed to connect to <url> (port 80): connect failed: ETIMEDOUT (connection timed out)
这是我进行网络调用的 AsyncTask。
private class PostToPHP extends AsyncTask<PostToPHP, Void, String>
{
private String functionName;
private ArrayList<NameValuePair> postKeyValuePairs;
public PostToPHP(String function, ArrayList<NameValuePair> keyValuePairs)
{
functionName= function;
postKeyValuePairs = keyValuePairs;
}
@Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(BaseActivity.getInstance(), "Loading", "Please wait...", true, false);
}
@Override
protected String doInBackground(PostToPHP... params)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(FUNCTION_NAME, functionName));
for (int i = 0; i < postKeyValuePairs.size(); i++) {
nameValuePairs.add(postKeyValuePairs.get(i));
}
try {
URL url = new URL("www.myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-Charset", iso-8859-1);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, iso-8859-1));
writer.write(getEncodedPostParameters(nameValuePairs, iso-8859-1));
writer.close();
os.close();
InputStream is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, iso-8859-1));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
urlConnection.disconnect();
return sb.toString();
}
catch (UnknownHostException e) {
// handle it
return null;
}
catch (Exception e) {
// this is where I'm always getting a timeout exception
return null;
}
}
@Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
}
编辑:我以为这只发生在一次特定的网络调用期间,但我现在在不同的地方都经历过这种情况。
编辑2:再次查看此内容,我发现 this我认为这更多的是我的问题。在我为网络调用实现 Android AsyncTask 之前,这是不存在的。我认为 AsyncTask 在某种程度上搞砸了线程并导致超时。
最佳答案
您可以显式设置 HTTPUrlConnection 的超时:
urlConnection.setConnectionTimeout(aLongerTimeout)
关于java - 为什么我的 Android 应用程序中不断出现 java.net.ConnectException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315213/