【问题标题】:Socket closed exception when trying to read httpResponse尝试读取 httpResponse 时套接字关闭异常
【发布时间】:2013-10-10 12:27:30
【问题描述】:

我有一种方法可以连接以将发布数据发送到网络服务并获得如下响应:

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;
}

然后,在我的片段的 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;
                }
            }

当我到达那条线时:

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

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

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

【问题讨论】:

  • 因为您在调用httpClient.execute 之后调用HttpPost.abortAndroidHttpClient.close,而不是在读取来自Httpresponse 的响应之后

标签: android sockets httpresponse androidhttpclient


【解决方案1】:

在使用使用 HttpClientBuilder 构建的客户端实例时,我也遇到了“套接字关闭”异常。就我而言,在处理响应对象(在父方法中)之前,我在 finally 块中对我的请求对象调用 HttpRequestBase.releaseConnection() 。翻转东西解决了这个问题......(下面的工作代码)

    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();
    }

【讨论】:

    【解决方案2】:

    随便写

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

    它应该可以工作。无需编写令人困惑的代码。

    【讨论】:

    • 从 AndroidHttpClient 更改为 DefaultHttpClient 似乎已经解决了这个问题。
    • DefaultHttpClient 已被弃用。请改用 HttpClientBuilder。
    猜你喜欢
    • 2018-05-18
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 2012-10-24
    相关资源
    最近更新 更多