如何使用 Java 在 Http Get 方法中设置 Cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3249137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Cookies at Http Get method using Java
提问by fysob
I want to do a manual GET with cookies in order to download and parse a web page. 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) ). I then wrote the String containing the cookies like this:
我想使用 cookie 进行手动 GET,以便下载和解析网页。我需要提取安全令牌,以便在论坛上发帖。我已经完成了登录,阅读了响应并提取了 cookie(3 对 (name,value) )。然后我写了包含 cookie 的字符串,如下所示:
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. 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. I will check the link you gave me and hopefully will find a solution.
编辑:我知道如果我想发帖,我必须提取安全令牌。我的思路是,为了提取它,我需要获取这个特定的页面。但是为了将安全令牌作为隐藏字段,我必须在线,因此我需要 cookie。但是,当我获取页面并如上所述设置 cookie 时,我以访客身份获取页面,这表明我不在线并且安全令牌的值是访客,这对我没有用。我会检查你给我的链接,希望能找到解决方案。
回答by BalusC
To be sure, you should be gathering the cookies from the response's Set-Cookie
headers. To send them back in the subsequent requests, you should set them one by one using URLConnection#addRequestProperty()
.
可以肯定的是,您应该从响应的Set-Cookie
标头中收集 cookie 。要在后续请求中将它们发回,您应该使用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的属性expires
,path
等等。
For a more convenienced HTTP client I'd suggest to have a look at Apache HttpComponents Client. It can handle all the cookie stuff more transparently.
对于更方便的 HTTP 客户端,我建议查看Apache HttpComponents Client。它可以更透明地处理所有 cookie 内容。
See also:
也可以看看:
Update: as per the comments, this is not a cookie problem. A wrong request token means that the server has CSRF/bot prevention builtin (to prevent people like you). 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. Jsoupmay be useful to extract all (hidden) input fields. 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.
更新:根据评论,这不是 cookie 问题。错误的请求令牌意味着服务器内置了 CSRF/bot 防护(以防止像你这样的人)。您需要使用表单从请求的页面中提取令牌作为隐藏的输入字段,并将其作为请求参数重新发送。Jsoup可能有助于提取所有(隐藏的)输入字段。不要忘记传递您希望以编程方式“按下”的按钮的名称-值对。另请参阅上述链接以获取更多提示。
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.
将来,您真的应该更加清楚检索到的确切错误,而不是随意猜测。复制粘贴确切的错误信息等等。
回答by finnw
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,并将它们与下一个请求一起发送回同一主机。
回答by Rohit Haval
// 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. The working code is:
上面的代码适用于发送多个 cookie,只需使用 setRequestProperty 而不是 addRequestProperty。工作代码是:
// 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]);
}