有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

未收到python Java HTTP cookies

因此,我尝试使用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。我已经确认它在工作,但是饼干是空的。使用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);

甚至Python的请求库也接收cookie。我还测试了使用http://requestmaker.com/查看发送的头,它能够接收头中的cookie。使用与requestmaker相同的头。com,我仍然无法收到cookies

问题是:这些库有什么是我的HttpsUrlConnection没有的


共 (1) 个答案

  1. # 1 楼答案

    解决方案是使用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();