无法获取响应代码!指针?
问题描述:
我正在尝试抓取300,000个网址。但是,在中间的某处,代码在尝试从URL检索响应代码时会挂起。我不确定自建立连接以来发生了什么问题,但之后发生了问题。我修改了设置读取超时和请求属性的代码,但是,即使现在代码也无法获得响应代码! 任何建议/指针将不胜感激。另外,是否有任何方法可以在一段时间内ping一个网站,如果它没有响应,就继续下一个网站?无法获取响应代码!指针?
这是我修改后的代码片段:
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;
}
答
由于响应代码从未在字节流中收到,所以挂起。你会想看看一个http调试器,看看实际收到了什么,如果有的话。它似乎打开了到服务器的TCP连接。它可能不喜欢您的用户代理(可能没有设置您的想法)或HEAD
的请求方法,也可能是带宽有限的服务器。您可以使用Socket
类来打开一个连接,并手动准备好字节以查看您的/未收到的内容。
在附注中,仅使用Socket
实际上并不是一个坏方法,具体取决于您想要做什么。它听起来像就像你正在写一个HTTP服务器检查器,在这种情况下,你将得到更多的功能,直接使用Socket
直接,因为你将能够设计更好的和更多的优化技术(你正在与大量的低毕竟是网络级别的io)。
答
您设置读取并在HttpURLConnection的连接超时你叫url.openConnection后(),它打开连接。因此他们没有生效。我可能会使用Jetty HttpClient来达到此目的,而不是Java URL类。
回答你的第二点。是的,只需尝试使用原始套接字在远程域名处打开与端口80(或其他端口,如果在URL中指定的端口)的连接即可从URL中提取(使用url.getHost()
)。为此,我将使用Netty而不是Java套接字。
感谢您的回复!我会研究他们 – collegian 2011-04-22 17:17:57