使用Java URLConnection关闭Cookie

dha*_*rga 8 java http-headers

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

<div class="body"><p>Your browser's cookie functionality is turned off. Please turn it on.
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)

ZZ *_*der 10

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

  CookieHandler.setDefault(new CookieManager());
Run Code Online (Sandbox Code Playgroud)

URLConnection的cookie处理非常弱.它几乎没有用.它无法正确处理所有cookie规则.如果您正在处理敏感cookie(如身份验证),则应使用Apache HttpClient.