使用 Java 中的 HTTP 请求发送 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2528935/
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
Sending cookie with HTTP request in Java
提问by nkr1pt
I'm trying to get a certain cookie in a java client by creating a series of Http requests. It looks like I'm getting a valid cookie from the server but when I'm sending out a request to the fnal url with the seemingly valid cookie I should get some lines of XML in the response but the response is blank because the cookie is wrong or is invalidated because a session has closed or an other problem which I can't figure out. The cookie handed out by the server expires at the end of the session.
我试图通过创建一系列 Http 请求在 Java 客户端中获取某个 cookie。看起来我从服务器获取了一个有效的 cookie,但是当我使用看似有效的 cookie 向最终 url 发送请求时,我应该在响应中得到一些 XML 行,但响应为空,因为 cookie 是错误或无效,因为会话已关闭或我无法弄清楚的其他问题。服务器分发的 cookie 在会话结束时过期。
It seems to me the cookie is valid because when I do the same calls in Firefox, a similar cookie with the same name and starting with the 3 first same letters and of the same length is stored in firefox, also expiring at the end of the session. If I then make a request to the final url with only this particular cookie stored in firefox (removed all other cookies), the xml is nicely rendered on the page.
在我看来,cookie 是有效的,因为当我在 Firefox 中执行相同的调用时,具有相同名称且以前 3 个相同字母开头且长度相同的类似 cookie 存储在 firefox 中,并在结束时到期会议。如果我然后仅使用存储在 firefox 中的这个特定 cookie(删除所有其他 cookie)向最终 url 发出请求,则 xml 会很好地呈现在页面上。
Any ideas about what I am doing wrong in this piece of code? One other thing, when I use the value from the very similar cookie generated and stored in Firefox in this piece of code, the last request does give XML feedback in the HTTP response.
关于我在这段代码中做错了什么的任何想法?另一件事,当我在这段代码中使用非常相似的 cookie 中生成并存储在 Firefox 中的值时,最后一个请求确实在 HTTP 响应中提供了 XML 反馈。
// Validate
url = new URL(URL_VALIDATE);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
if (conn.getHeaderField(i).startsWith("JSESSIONID")) {
cookie = conn.getHeaderField(i).substring(0, conn.getHeaderField(i).indexOf(";")).trim();
}
}
}
// Get the XML
url = new URL(URL_XML_TOTALS);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.connect();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
reader.close();
//Output the response
System.out.println(answer.toString())
采纳答案by McDowell
I'm feeling a bit too lazy to debug your code, but you might consider letting a CookieHandlerdo the heavy lifting. Here's one I made earlier:
我感觉有点懒得调试您的代码,但您可以考虑让CookieHandler 来完成繁重的工作。这是我之前做的一个:
public class MyCookieHandler extends CookieHandler {
private final Map<String, List<String>> cookies =
new HashMap<String, List<String>>();
@Override public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> ret = new HashMap<String, List<String>>();
synchronized (cookies) {
List<String> store = cookies.get(uri.getHost());
if (store != null) {
store = Collections.unmodifiableList(store);
ret.put("Cookie", store);
}
}
return Collections.unmodifiableMap(ret);
}
@Override public void put(URI uri, Map<String, List<String>> responseHeaders)
throws IOException {
List<String> newCookies = responseHeaders.get("Set-Cookie");
if (newCookies != null) {
synchronized (cookies) {
List<String> store = cookies.get(uri.getHost());
if (store == null) {
store = new ArrayList<String>();
cookies.put(uri.getHost(), store);
}
store.addAll(newCookies);
}
}
}
}
The CookieHandler
assumes your cookie handling is global to the JVM; if you want per-thread client sessions or some other more complicated transaction handling, you may be better off sticking with your manual approach.
该CookieHandler
假定您的cookie处理是全球的JVM; 如果您想要每线程客户端会话或其他一些更复杂的事务处理,最好坚持使用手动方法。