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();  
        }  
    }  
}  

果然没问题了,这里记录下!

文章最后编辑时间为:2017-01-25 17:49:57

标签: java httpurlconn

声明:本博客如无特殊说明皆为原创,转载请注明来源:Java - 网络爬虫httpUrlConn.getResponseCode()取不到值的问题谢谢!

相关文章

发表评论:

icon_question.pngicon_razz.pngicon_sad.pngicon_evil.pngicon_exclaim.pngicon_smile.pngicon_redface.pngicon_biggrin.pngicon_surprised.pngicon_eek.pngicon_confused.pngicon_cool.pngicon_lol.pngicon_mad.pngicon_twisted.pngicon_rolleyes.pngicon_wink.pngicon_idea.pngicon_arrow.pngicon_neutral.pngicon_cry.pngicon_mrgreen.png