Software caused connection abort: recv failed
java .net .SocketException: Software caused connection abort: recv failed
at java .net .SocketInputStream.socketRead0(Native Method)
at java .net .SocketInputStream.read(SocketInputStream.java :32)
产生这个异常的原因有多种方面
是由于程序编写的问题,而不是网络的问题引起的.
总结产生原因,在服务端/客户端单方面关闭连接的情况下,另一方依然以为
tcp连接仍然建立,试图读取对方的响应数据,导致出现
Software caused connection abort: recv failed 的异常.
解决方式:每次请求都要释放连接,在对方释放连接后,也要释放本地的连接.
public static JSONObject postJson(String url, String json) throws Exception{
CloseableHttpClient httpclientPost = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
JSONObject response = null;
post.setConfig(requestConfig);
System.err.println("begin at " + new Date().getTime());
CloseableHttpResponse res = null;
try {
StringEntity s = new StringEntity(json, ContentType.APPLICATION_JSON);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");// 发送json数据需要设置contentType
post.setEntity(s);
res = httpclientPost.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
System.err.println("end at " + new Date().getTime());
throw e;
} finally {
try {
if (res != null) {
res.close();
}
post.releaseConnection();
httpclientPost.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}