未收到Java HTTP cookies

未收到Java HTTP cookies,java,python,cookies,Java,Python,Cookies,因此,我尝试使用Java中的HttpsUrlConnection从网站()接收cookie,但它不会发送cookie作为响应。令人惊讶的是,像ApacheHttpClient这样的库能够接收cookie。甚至Python的请求库也可以工作 我的代码: URL obj = new URL("https://account.mojang.com/login"); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(

因此,我尝试使用Java中的HttpsUrlConnection从网站()接收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。我已经确认它在工作,但是饼干是空的。使用ApacheHttpClient,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);
final-HttpClient-client=HttpClientBuilder.create().build();
最终HttpPost登录成本=新HttpPost(“https://account.mojang.com/login");
loginPost.setHeader(“用户代理”、“Mozilla/5.0(Windows NT 10.0;WOW64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/52.0.2743.116 Safari/537.36”);
最终列表loginparms=new ArrayList();
添加(新的BasicNameValuePair(“用户名”,电子邮件));
添加(新的BasicNameValuePair(“密码”,password));
loginPost.setEntity(新的UrlEncodedFormEntity(loginparms));
客户。执行(登录成本);
甚至Python的请求库也接收cookie。我还测试了查看发送的标头,它能够接收标头中的cookie。使用与requestmaker.com相同的标题,我仍然无法接收cookies


问题是:这些库有哪些是我的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();