HttpUrlConnection java.net.SocketException: Software caused connection abort: recv failed

最近做java swing程序在模拟httprequest请求的时候出现了这个错误

 java.net.SocketException: Software caused connection abort: recv failed

显示是在connection在获得con.getInputStream()时随机出现这个exception,

最后我感觉是 16行把输出流关闭了,这个时候server会认为连接已断开,于是该把16行放到27行,不知道对不对。

 1      HttpURLConnection con = (HttpURLConnection) url.openConnection();
 2         con.setRequestMethod(requestMethod);
 3         con.setDoInput(true);
 4         con.setDoOutput(true);
 5         con.setUseCaches(true);
 6         con.setRequestProperty("Content-Type", contentType);
 7         con.setRequestProperty("Accept-Charset", charset);
 8 
 9         DataOutputStream printout = new DataOutputStream(con.getOutputStream());
10 
11         // This is the POST
12         // String content = "type=ask_bid_list_table&symbol="+coinName+"_cny";
13 
14         printout.writeBytes(content);
15         printout.flush();
16         printout.close();
17         if (con.getResponseCode() == 200) {
18             BufferedReader input = new BufferedReader(new InputStreamReader(
19                     con.getInputStream(), charset));
20             String str;
21             StringBuilder sb = new StringBuilder();
22             // Read the response
23 
24             while (null != ((str = input.readLine()))) {
25                 sb.append(str);
26             }
27 
28             input.close();
        }

 这个错误只是随机出现。

原文地址:https://www.cnblogs.com/fengjian/p/3481004.html