Java HttpURLConnection - 使用Cookie进行POST请求

11

我正在尝试使用cookies发送POST请求。这是代码:

try {

    String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
    String cookies = "session_cookie=value";
    URL url = new URL("https://myweb");
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setRequestProperty("Cookie", cookies);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.writeBytes(query);
    out.flush();
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String decodedString;
    while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
    }
    in.close();

    // Send the request to the server
    //conn.connect();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
问题在于请求没有携带cookies。如果我只执行conn.connect();而不发送数据,则cookies会被正确发送。由于连接是通过SSL进行的,所以无法准确检测发生了什么。我只能检查响应。
1个回答

6
根据 URLConnection javadoc 的说明:
The following methods are used to access the header fields and the 
contents AFTER the connection is made to the remote object:

* getContent
* getHeaderField
* getInputStream
* getOutputStream

您确定在上述测试用例中请求是否已经到达服务器了吗?我看到您在getOutputStream()之后注释掉了对connect()的调用。如果您取消注释并将其移动到getOutputStream()之前会发生什么呢?


谢谢!我再次尝试在服务器上重写PHP代码,现在它完美地工作了。我发布的代码没问题。我认为问题出在服务器上(可能是我写成了$_POST[$key]而不是$_POST['key']之类的错误)。 - Alberto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接