我有一种方法可以连接以将发布数据发送到网络服务并获得回复,如下所示:
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
。
这种行为不会一直发生,也许每隔一段时间都会发生。
答案 0 :(得分:6)
只需写下
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
它应该工作。不需要编写会造成混淆的代码。
答案 1 :(得分: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();
}