Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

http headers - Cookies turned off with Java URLConnection

I am trying to make a request to a webpage that requires cookies. I'm using HTTPUrlConnection, but the response always comes back saying

<div class="body"><p>Your browser's cookie functionality is turned off. Please turn it on.

How can I make the request such that the queried server thinks I have cookies turned on. My code goes something like this.

private String readPage(String page) throws MalformedURLException {
    try {
        URL url = new URL(page);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.connect();

        InputStream in = uc.getInputStream();
        int v;
        while( (v = in.read()) != -1){
            sb.append((char)v);
        }
        in.close();
        uc.disconnect();
    } catch (IOException e){
        e.printStackTrace();
    }
    return sb.toString();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to add a CookieHandler to the system for it handle cookie. Before Java 6, there is no CookieHandler implementation in the JRE, you have to write your own. If you are on Java 6, you can do this,

  CookieHandler.setDefault(new CookieManager());

URLConnection's cookie handling is really weak. It barely works. It doesn't handle all the cookie rules correctly. You should use Apache HttpClient if you are dealing with sensitive cookies like authentication.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...