HttpURLConnection 带 cookie 请求 ?

url = "http://www.baidu.com";
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
String cookieval = conn.getHeaderField("set-cookie");
String sessionid = null;

    if(cookieval != null){ 
        sessionid = cookieval.substring(0, cookieval.indexOf(";"));
        conn.addRequestProperty("Cookie", sessionid);
    }

    conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    conn.setRequestProperty("Accept-Encoding","gzip, deflate, sdch");
    conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8");
    conn.setRequestProperty("Cache-Control","max-age=0");
    conn.setRequestProperty("Connection","keep-alive");
    conn.setRequestProperty("Upgrade-Insecure-Requests","1");
    conn.setRequestProperty("Cookie",sessionid);
    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");

    conn.connect();
    int code = conn.getResponseCode();


    这样抛异常:Exception in thread "main" java.lang.IllegalStateException: Already connected
at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(HttpURLConnection.java:2256)
at com.huruxi.practice.http.HttpURLTest.getWebData(HttpURLTest.java:26)
at com.huruxi.practice.http.HttpURLTest.main(HttpURLTest.java:87)

通过HttpURLConnection 访问网站,网站需要带cookie,我这样先获取,在设置cookie有异常,如果在浏览器中访问网站拷贝cookie来执行是可以的
技术较弱,大牛海涵,

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问