http请求循环调用返回数据抓取不全解决

最近碰到一个问题,就是频繁调用http请求,返回的数据出现缺失的情况。特此记录下解决过程。

先上代码  普通的get调用方法

    public String sendGet(String urlStr) throws InterruptedException {
        try {
            //获取httpURLConnection对象
            URL url = new URL(urlStr);
            HttpURLConnection httpURLConnection = (
                    HttpURLConnection) url.openConnection();
            //设置连接属性
            httpURLConnection.setConnectTimeout(60000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            //获取相应状态码
            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                String jsonStr = "";
                InputStream inputStream=httpURLConnection.getInputStream();
                // ByteArrayOutputStream相当于内存输出流
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                // 将输入流转移到内存输出流中
                try {
                    while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    // 将内存流转换为字符串
                    jsonStr = new String(out.toByteArray());
                } catch (IOException e) {
                    log.error("", e);
                }
                return jsonStr;

            }
        } catch (MalformedURLException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
        return "";
    }

测试方法:

public static void main(String[] args) throws InterruptedException {
        HttpUtil httpUtil = new HttpUtil();
        for (int i = 0; i < 100; i++) {
            System.out.println("result:"+"-"+i+httpUtil.sendGet("http://ip.taobao.com/service/getIpInfo.php?ip=1.1.1.1"));

        }
      

    }

简化成一个for循环,去调用一个接口。输出如下

可以看到有些请求返回数据完整,有些缺了部分,有些根本获取不到。

单个请求是能完整获取到的,应该就是频繁获取的原因,有人说设置超时时间,可我设置了根本没用。我觉得应该设置请求调用时的间隔时长,所以加了句Thread.currentThread().sleep(500)。如果仍然出现,时间可以再长点。

然后就正常了。不知还有没有其他的解决方案。请大神指教。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值