因此,我尝试使用Java中的HttpsUrlConnection从网站(https://account.mojang.com/login)接收cookie,但它没有发送cookie作为响应。令人惊讶的是,像apachehttpclient这样的库能够接收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());
上面的代码不接收cookies。我已经确认它在工作,但是饼干是空的。使用Apache HttpClient,cookies不是空的。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的请求库也会收到cookies。我还测试了使用http://requestmaker.com/查看发送的头,它能够接收头中的cookie。使用与相同的标题requestmaker.com网站,我仍然无法收到饼干。你知道吗
问题是:这些库有什么是我的HttpsUrlConnection没有的?你知道吗
解决方案是使用CookieHandler:
相关问题 更多 >
编程相关推荐