使用Java URLConnection关闭Cookie [英] Cookies turned off with Java URLConnection

查看:410
本文介绍了使用Java URLConnection关闭Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向需要Cookie的网页发出请求。我正在使用HTTPUrlConnection,但响应总是回来说

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.

我如何发出请求,以便被查询的服务器认为我已打开cookie。我的代码是这样的。

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


推荐答案

你需要添加一个CookieHandler系统为它处理cookie。在Java 6之前,JRE中没有CookieHandler实现,您必须自己编写。如果您使用的是Java 6,则可以执行此操作,

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的cookie处理非常弱。它几乎没有用。它没有正确处理所有cookie规则。如果您正在处理敏感cookie,如身份验证,则应使用Apache HttpClient。

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.

这篇关于使用Java URLConnection关闭Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆