3

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.

Distwo
  • 11,569
  • 8
  • 42
  • 65
  • 2
    because you are calling `HttpPost.abort` and `AndroidHttpClient.close` just after calling `httpClient.execute` instead of after reading response from Httpresponse – ρяσѕρєя K Oct 03 '13 at 17:35

2 Answers2

6

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.

Ranjit
  • 5,130
  • 3
  • 30
  • 66
1

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();
    }
John Rix
  • 6,271
  • 5
  • 40
  • 46