Android - HttpClient.execute(HttpPost) randomly throws IOException (Connection refused)

459 views Asked by At

I have created a class to handle API request by extended from AsyncTask<String,String,byte[]>. Randomly the part response = client.execute(post); throwing IO error with the message Connection to [URL] refused

@Override protected byte[] doInBackground(String... uri) {
    ArrayList<NameValuePair> list = this.params==null?null:new ArrayList<NameValuePair>(this.params.size());
    byte[] result = null;
    HashMap<String,Object> iterated = this.params==null?null:(HashMap<String, Object>) this.params.clone();
    if(iterated!=null&&iterated.size()!=0) try{
        Iterator iterator = iterated.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry pair = (Map.Entry)iterator.next();
            String key = String.valueOf(pair.getKey());
            String val = String.valueOf(pair.getValue());
            if(list!=null) list.add(new BasicNameValuePair(key,val));
            iterator.remove();
        }
    }catch(UnsupportedEncodingException ex){
        return null;
    }
    HttpPost post = new HttpPost(this.url);
    try{
        if(list!=null) post.setEntity(new UrlEncodedFormEntity(list));
    }catch(UnsupportedEncodingException ex){
        return null;
    }
    if(isCancelled()||post.isAborted()) return null;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, this.timeout);
    HttpClient client = new DefaultHttpClient(httpParams);
    HttpResponse response;
    try{
        response = client.execute(post);
    }catch(ClientProtocolException ex){
        return null;
    }catch(IOException ex) {
        return null;
    }
    StatusLine status = response.getStatusLine();
    if(isCancelled()||post.isAborted()) return null;
    if(status.getStatusCode() == HttpStatus.SC_OK) try{
        if(response.getEntity()==null) return null;
        Header responsetype = response.getEntity().getContentType();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        result = out.toByteArray();
    }catch(IOException ex){}
    else response.getEntity().getContent().close();
    return result;
}

These are some logged texts

06-24 16:08:25.825: I/System.out(12858): Url : http://www.x.com/api/index.php/notification/listNotification
06-24 16:08:25.825: I/System.out(12858): Parameters : {loginkey=sa119k338r4chtr3}
06-24 16:08:28.855: I/System.out(12858): IOException : Connection to http://www.x.com refused
0

There are 0 answers