应用程序释放IOUtils.toString()

时间:2016-09-10 18:10:15

标签: java socrata

我有一个应用程序,我需要使用他们的API从(Socrata)数据集中读取一些开放数据。由于该数据集上有很多记录,我通过一段时间内使用偏移来循环它

//initialize variables
//...
do{
    System.out.println("1");
    BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url+offset).openStream()));
    String reply=IOUtils.toString( in );
    //read the page to a String and convert to JSON
    JSONObject obj = new JSONObject(reply);
    //close connection
    in.close();
    JSONArray results=obj.getJSONArray("results");
            //do something here 
    offset+=100;
}while(results.length()!=0&&offset<=endOffset);     

这似乎在几次迭代(大约20-50)中工作正常,但随后无缘无故并且不总是在相同的偏移量上,它只是挂起后

String reply=IOUtils.toString( in );

永远。
我尝试使用番石榴,因为post建议没有区别 这个

String reply = CharStreams.toString( new InputStreamReader( new URL(runHost+offset).openStream(), "UTF-8" ) ); 
来自here

似乎做得更好,但在大约70次迭代后再次被绞死。

如果有很长的延迟并且继续执行程序的其余部分,是否至少有一种方法可以停止循环?(作为最坏的情况)
修改
关于@Mad Matts推荐,结果是从我从API获得的JSONObject转换的JSONArray。(代码更新)
我在条件下使用&&,因为如果数组不为空(results.length()!=0)并且偏移量小于endOffset,我需要重复循环。最后一部分我用它来避免挂起程序。我至少可以一次运行10次偏移,得到我的结果并在接下来的10次偏移中再次运行,依此类推。

0 个答案:

没有答案