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

查看:21
本文介绍了使用 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天全站免登陆