gpt4 book ai didi

java - 使用 Java URLConnection 关闭 Cookie

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:03 26 4
gpt4 key购买 nike

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

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

我怎样才能发出请求,使被查询的服务器认为我打开了 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();
}

最佳答案

您需要在系统中添加一个CookieHandler 来处理cookie。 Java 6之前,JRE中没有CookieHandler的实现,得自己写。如果你使用的是 Java 6,你可以这样做,

  CookieHandler.setDefault(new CookieManager());

URLConnection 的 cookie 处理非常薄弱。它几乎不起作用。它没有正确处理所有 cookie 规则。如果您要处理身份验证等敏感 cookie,则应使用 Apache HttpClient。

关于java - 使用 Java URLConnection 关闭 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1455856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com