Search code examples
androidsocketshttpresponseandroidhttpclient

Socket closed exception when trying to read httpResponse


I have a method to connect to send post data to a webservice and get the response back as follow:

public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
    HttpResponse response = null;

    AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
    HttpPost post = new HttpPost(url);

    StringEntity str = new StringEntity(xml);
    str.setContentType("text/xml");
    post.setEntity(str);

    response = httpClient.execute(post);

    if (post != null){
        post.abort();
    }
    if (httpClient !=null){
        httpClient.close();
    }

    return response;
}

Then, in my AsyncTask of my fragment, I try to read the response using getEntity():

HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");

            //Check if the request was sent successfully
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // Parse result to check success
                responseText = EntityUtils.toString(response.getEntity());

                if (!xmlParser.checkForSuccess(responseText, getActivity())){
                    //If webservice response is error
                    ///TODO: Error management
                    return false;
                }
            }

And when I reach that line:

responseText = EntityUtils.toString(response.getEntity());

I get an exception: java.net.SocketException: Socket closed.

This behavior doesn't happen all the time, maybe every other time.


Solution

  • Just write

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(your url);
    HttpResponse response = client.execute(post);
    

    it should work.No need to write codes which makes confusion.