我正在尝试向需要 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!