Distwo
Distwo

Reputation: 11759

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.

Upvotes: 3

Views: 6608

Answers (2)

John Rix
John Rix

Reputation: 6703

I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)

    try {
        HttpResponse response = httpClient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity());
        // Do something interesting with responseBody       
    } catch (IOException e) {
        // Ah nuts...
    } finally {
        // release any connection resources used by the method
        request.releaseConnection();
    }

Upvotes: 1

Ranjit
Ranjit

Reputation: 5150

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.

Upvotes: 6

Related Questions