我有一种方法可以连接将发布数据发送到 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;
}
然后,在我的片段的 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
.
这种行为不会一直发生,也许每隔一段时间就会发生一次。