Android 尝试读取httpResponse时套接字关闭异常
我有一个连接方法,可以将post数据发送到Web服务,并按如下方式返回响应:Android 尝试读取httpResponse时套接字关闭异常,android,sockets,httpresponse,androidhttpclient,Android,Sockets,Httpresponse,Androidhttpclient,我有一个连接方法,可以将post数据发送到Web服务,并按如下方式返回响应: public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException { HttpResponse response = null; AndroidHttpClient httpClient = AndroidHttpClient.newInstance(ht
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()读取响应:
当我到达那条线时:
responseText = EntityUtils.toString(response.getEntity());
我得到一个异常:java.net.SocketException:socketclosed
这种行为并非总是发生,可能每隔一次就发生一次。只要写下就行了
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
它应该可以工作。不需要编写会引起混淆的代码。在使用使用HttpClientBuilder构建的客户端实例时,我也遇到了“套接字关闭”异常。在我的例子中,在处理响应对象(在父方法中)之前,我在finally块中对请求对象调用了HttpRequestBase.releaseConnection()。翻来覆去解决了这个问题。。。(工作代码如下)
因为您正在调用
HttpPost.abort
和AndroidHttpClient.close
就在调用httpClient.execute之后,而不是在读取来自httpresponse的响应之后。从AndroidHttpClient到DefaultHttpClient的更改似乎已经解决了这个问题。DefaultHttpClient已被弃用。改用HttpClientBuilder。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
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();
}