boltup_im_coding
boltup_im_coding

Reputation: 6665

Why do I keep getting java.net.ConnectException in my Android application?

I have recently refactored some of my networking code in my android app to use the Google recommended HTTPUrlConnection. Previously, I was using Apache's HTTPClient. I'm not sure if either of those things are relevant.

The other thing I have recently done to my networking code is use AsyncTask for the calls. Previously I was just doing work on the main thread (obviously bad) and so my application would appear to hang when fetching data. The thing is, since switching to AsyncTask, I have pretty regularly experienced timeout errors.

Why do I get this timeout error?

 java.net.ConnectException: failed to connect to <url> (port 80): connect failed: ETIMEDOUT (connection timed out)

Here is my AsyncTask that makes the network call.

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();
    }
}

EDIT: I thought this only occurred during one particular network call but I've now experienced it at various places.

EDIT 2: Looking at this again I found this and I think that's more of my problem. This didn't exist before I implemented Android AsyncTask for the network calls. I think that AsyncTask is somehow screwing up with threading and causing the timeouts.

Upvotes: 2

Views: 4765

Answers (2)

boltup_im_coding
boltup_im_coding

Reputation: 6665

I'm not very satisfied with this answer, but it seems to be working. I think there must be an issue with my code, or a bug in HTTPUrlConnection of some sort. I know Google said it had bugs in Froyo and lower, but I'm seeing oddities in 2.3.4 and 4.2 which I'm testing with. Essentially I replaced my code above with Apache's code and I'm not seeing the timeouts.

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();
}

Upvotes: 1

Jeremy
Jeremy

Reputation: 831

You could explicitly set the timeout for the HTTPUrlConnection:
urlConnection.setConnectionTimeout(aLongerTimeout)

Upvotes: 1

Related Questions