尝试读取httpResponse时套接字关闭异常

Dis*_*two 2 sockets android httpresponse androidhttpclient

我有一个方法连接发送数据到Web服务并获得响应如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的片段的AsyncTask中,我尝试使用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;
                }
            }
Run Code Online (Sandbox Code Playgroud)

当我到达那条线时:

responseText = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

我得到一个例外:java.net.SocketException: Socket closed.

这种行为不会一直发生,可能每隔一段时间发生一次.

Ran*_*jit 6

写吧

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
Run Code Online (Sandbox Code Playgroud)

它应该工作.不需要编写令混乱的代码.

  • 从AndroidHttpClient更改为DefaultHttpClient似乎已修复此问题. (2认同)