简体   繁体   English

如何使用Java在Http Get方法中设置Cookies

[英]How to set Cookies at Http Get method using Java

I want to do a manual GET with cookies in order to download and parse a web page. 我想用cookies手动GET以下载和解析网页。 I need to extract the security token, in order to make a post at the forum. 我需要提取安全令牌,以便在论坛上发帖。 I have completed the login, have read the response and extracted the cookies (3 pairs of (name,value) ). 我已完成登录,已阅读响应并提取了cookie(3对(名称,值))。 I then wrote the String containing the cookies like this: 然后我写了包含这样的cookie的String:

CookieString="name1=value1; name2=value2; name3=value3"

I then do the following 然后我做以下事情

HttpURLConnection connection
connection = (HttpURLConnection)(new URL(Link).openConnection());
connection.setRequestMethod("GET");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cookie", CookieString );
connection.connect();

I then read the page but it shows that I am not logged at the forum. 然后我阅读了该页面,但它显示我没有登录论坛。 What am I doing wrong? 我究竟做错了什么?

edit: I know that I must extract the security token if I want to make a post. 编辑:我知道如果我想发帖,我必须提取安全令牌。 My train of thought was that in order to extract it, I need to GET this particular page. 我的思路是,为了提取它,我需要获取这个特定的页面。 But for the security token to be as a hidden field I must be online, thus I needed the cookies. 但是为了将安全令牌作为隐藏字段,我必须在线,因此我需要cookie。 But when I GET the page and I set the cookies as mentioned above i get the page as a guest, it shows that I am not online and the value of security token is guest which is not useful for me. 但是,当我获取页面并设置上面提到的cookie时,我将该页面作为访客,它表明我不在线,安全令牌的值是guest,这对我没用。 I will check the link you gave me and hopefully will find a solution. 我会检查你给我的链接,希望能找到解决方案。

To be sure, you should be gathering the cookies from the response's Set-Cookie headers. 当然,您应该从响应的Set-Cookie标头中收集cookie。 To send them back in the subsequent requests, you should set them one by one using URLConnection#addRequestProperty() . 要在后续请求中将它们发回,您应该使用URLConnection#addRequestProperty()逐个设置它们。

Basically: 基本上:

// ...

// Grab Set-Cookie headers:
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

// ...

// Send them back in subsequent requests:
for (String cookie : cookies) {
    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}

// ...

The split(";", 2) is there to get rid of cookie attributes which are irrelevant for the server side like expires , path , etc. split(";", 2)是为了摆脱与服务器端无关的cookie属性,如expirespath等。

For a more convenienced HTTP client I'd suggest to have a look at Apache HttpComponents Client . 为了更方便的HTTP客户端,我建议看一下Apache HttpComponents Client It can handle all the cookie stuff more transparently. 它可以更透明地处理所有cookie的内容。

See also: 也可以看看:


Update : as per the comments, this is not a cookie problem. 更新 :根据评论,这不是cookie问题。 A wrong request token means that the server has CSRF/bot prevention builtin (to prevent people like you). 错误的请求令牌意味着服务器内置了CSRF / bot预防(以防止像您这样的人)。 You need to extract the token as a hidden input field from the requested page with the form and resend it as a request parameter. 您需要使用表单从请求的页面中提取令牌作为隐藏的输入字段,并将其重新发送为请求参数。 Jsoup may be useful to extract all (hidden) input fields. Jsoup可能对提取所有(隐藏)输入字段很有用。 Don't forget to pass the name-value pair of the button as well which you'd like to "press" programmatically. 不要忘记传递按钮的名称 - 值对,您要以编程方式“按”。 Also see the abovementioned link for more hints. 另请参阅上述链接以获取更多提示。

In the future, you should really be more clear about the exact error you retrieve and not guess something in the wild. 在将来,你应该更清楚你检索到的确切错误,而不是在野外猜测。 Copypaste the exact error message and so on. Copypaste确切的错误消息等。

Assuming the cookie values are not hard-coded but obtained from a previous request, it's probably easiest to use the CookieHandler class. 假设cookie值不是硬编码的,而是从先前的请求获得的,那么使用CookieHandler类可能最容易。

CookieHandler.setDefault(new CookieManager());

Then your HttpURLConnection will automatically save any cookies it receives and send them back with the next request to the same host. 然后,您的HttpURLConnection将自动保存它收到的任何cookie,并将下一个请求发送回同一主机。

// Grab Set-Cookie headers:
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

// ...

// Send them back in subsequent requests:
for (String cookie : cookies) {
    connection.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}

Above code will work for sending multiple cookies just use setRequestProperty instead of addRequestProperty. 上面的代码可以用于发送多个cookie,只需使用setRequestProperty而不是addRequestProperty。 The working code is: 工作代码是:

// Grab Set-Cookie headers:
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

// ...

// Send them back in subsequent requests:
for (String cookie : cookies) {
    connection.setRequestProperty("Cookie", cookie.split(";", 1)[0]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM