java.io.IOException: Premature EOF
EOF错误
今天在开发过程中请求第三方接口遇到EOF异常,找了很多博客,总算是把问题解决了。
现将解决问题过程和大家进行分享。
问题出现原因:第三方接口可能没有发送http协议需要的结束行||此请求超过http抓包大小
原帖:https://stackoverflow.com/questions/13210108/reading-a-web-page-in-java-ioexception-premature-eof
解决方案:
public static String sendGet(String url, String... param) throws Exception {
StringBuffer sb = new StringBuffer();
BufferedReader in = null;
String urlName = "";
if (param.length == 0) {
urlName = url;
} else {
urlName = url + "?" + param[0].trim();
}
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 定义BufferedReader输入流来读取URL的响应
int BUFFER_SIZE = 1024;
char[] buffer = new char[BUFFER_SIZE]; // or some other size,
int charsRead = 0;
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(inputStreamReader);
while ((charsRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
sb.append(buffer, 0, charsRead);
}
if (in != null) {
in.close();
}
return sb.toString();
}