尝试获取响应代码时代码挂起。
我正在尝试抓取300,000个URL。但是,尝试从URL检索响应代码时,代码会挂在中间。我不确定发生了什么问题,因为正在建立连接,但是此后又出现了问题。任何建议/指针将不胜感激。此外,是否可以在特定时间段内对网站进行ping操作,如果它没有响应,请继续进行下一个操作?
我已根据建议修改了代码,并设置了读取超时和建议的request属性,但是即使是现在代码也无法获得响应代码!
这是我修改后的代码段:
URL url=null;
try
{
Thread.sleep(8000);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
try
{
//urlToBeCrawled comes from the database
url=new URL(urlToBeCrawled);
}
catch (MalformedURLException e)
{
e.printStackTrace();
//The code is in a loop,so the use of continue.I apologize for putting code in the catch block.
continue;
}
HttpURLConnection huc=null;
try
{
huc = (HttpURLConnection)url.openConnection();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
//Added the request property
huc.addRequestProperty(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\");
huc.setRequestMethod(\"HEAD\");
}
catch (ProtocolException e)
{
e.printStackTrace();
}
huc.setConnectTimeout(1000);
try
{
huc.connect();
}
catch (IOException e)
{
e.printStackTrace();
continue;
}
int responseCode=0;
try
{
//Sets the read timeout
huc.setReadTimeout(15000);
//Code hangs here for some URL which is random in each run
responseCode = huc.getResponseCode();
}
catch (IOException e)
{
huc.disconnect();
e.printStackTrace();
continue;
}
if (responseCode!=200)
{
huc.disconnect();
continue;
}
没有找到相关结果
已邀请:
2 个回复
玩翁文醚碱
类来修改用户代理(它们将其强制为您的JDK版本,例如:
将是您的用户代理。)有一些技巧可以通过调整系统属性,但我从未见过真正有效。再次使用Apache Commons HTTP库,您将不会后悔。 最终,您需要一个好的http调试器来最终解决此问题。您可以使用Fiddler2,只需设置一个Java代理来指向fiddler(滚动到有关Java的部分)。
畦桨存灯