最近碰到一个问题,就是频繁调用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)。如果仍然出现,时间可以再长点。
然后就正常了。不知还有没有其他的解决方案。请大神指教。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)