为什么我在Android应用程序中不断收到java.net.ConnectException?

时间:2013-03-09 19:54:58

标签: java android http networking

我最近在我的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在某种程度上搞砸了线程并导致超时。

2 个答案:

答案 0 :(得分:1)

您可以显式设置HTTPUrlConnection的超时:
urlConnection.setConnectionTimeout(aLongerTimeout)

答案 1 :(得分:1)

我对这个答案不是很满意,但似乎有效。我认为我的代码一定存在问题,或某种HTTPUrlConnection中的错误。我知道Google表示它在Froyo中存在错误并且较低,但我在2.3.4和4.2中看到了我正在测试的奇怪现象。基本上我用Apache的代码替换了上面的代码,我没有看到超时。

private static String post(ArrayList<NameValuePair> params){        
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpreq = new HttpPost("www.url.com");
    httpreq.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse response = httpclient.execute(httpreq);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is, NetworkConstants.HTTP_ACCEPTED_CHARSET), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();          

    return sb.toString();
}