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

标签 android sockets httpresponse androidhttpclient

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

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

然后,在我的 fragment 的 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 client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);

它应该可以工作。无需编写会造成混淆的代码。

关于android - 尝试读取 httpResponse 时套接字关闭异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19165420/

相关文章:

java - 操作栏背景大小,Android

java - 收集线程中的值并将其保存到 java 套接字数组中

java - 查找并获取网页发出的所有资源请求的响应码 - Java, Selenium

python - 我的基于 Django 的项目偶尔停止加载 View (Django 1.6)

java - 写入 http 响应对象的 OutputStream 后设置内容长度

android - 确定智能手机摄像头的视角

android - 检查 Playstore 中的内部测试人员是否安装了该应用程序

java - java中如何获取本地网络机器的MAC地址

java - 我可以向 InputStream 发送什么来表示已达到 EOF?

java - Android 中的实时音频处理