[英]Java HTTP cookies not received
因此,我尝试使用Java中的HttpsUrlConnection从网站( https://account.mojang.com/login )接收Cookie,但它不会发送Cookie作为响应。 令人惊讶的是,诸如Apache HttpClient之类的库能够接收cookie。 甚至Python的请求库也可以使用。
我的代码:
URL obj = new URL("https://account.mojang.com/login");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Host", "account.mojang.com");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(postPARAMS.length()));
//System.out.println(Integer.toString(postPARAMS.length()));
//con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
//con.setRequestProperty("Connection", "keep-alive");
//con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Accept", "*/*");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(postPARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
System.out.println("POST Response Code :: " + con.getResponseCode());
上面的代码未收到Cookie。 我已经确认它可以正常工作,但是Cookie为空。 使用Apache HttpClient,cookie不能为空。 Apache的代码如下所示:
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost loginPost = new HttpPost("https://account.mojang.com/login");
loginPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
final List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
loginParams.add(new BasicNameValuePair("username", email));
loginParams.add(new BasicNameValuePair("password", password));
loginPost.setEntity(new UrlEncodedFormEntity(loginParams));
client.execute(loginPost);
甚至Python的请求库也接收cookie。 我还测试了使用http://requestmaker.com/查看发送的标头,该标头能够接收标头中的cookie。 使用与requestmaker.com相同的标题,我仍然无法接收cookie。
问题是:这些库具有我的HttpsUrlConnection没有的库?
解决方案是使用CookieHandler:
URL obj = new URL("https://account.mojang.com/login");
CookieHandler.setDefault(new CookieManager()); //This line was not present before.
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.