Premature EOF 错误解决

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();
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值