Java - 网络爬虫httpUrlConn.getResponseCode()取不到值的问题
直接上代码,然而没什么用:
try {
URL pageUrl = new URL("http://www.baidu.com/");
HttpURLConnection httpUrlConn = (HttpURLConnection) pageUrl
.openConnection();
int statusCode = httpUrlConn.getResponseCode();
System.out.println(statusCode);
} catch (Exception e) {
e.printStackTrace();
}
网上找了点资料看了看,上面说,这个不能再main这个主线程中跑,要另起一个线程来运行。
于是我就试了下:
import java.net.HttpURLConnection;
import java.net.URL;
public class TestUrl {
public static void main(String[] args) {
Test t = new Test();
Thread demo = new Thread(t);
demo.start();
}
}
class Test implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
URL pageUrl = new URL("http://www.baidu.com/");
HttpURLConnection httpUrlConn = (HttpURLConnection) pageUrl
.openConnection();
int statusCode = httpUrlConn.getResponseCode();
System.out.println(statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
果然没问题了,这里记录下!