【问题标题】:Java HttpURLConnection - POST with CookieJava HttpURLConnection - 带有 Cookie 的 POST
【发布时间】:2011-07-28 17:10:13
【问题描述】:

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

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();
}

问题是发送的请求没有 cookie。如果我只做: 连接.connect();并且不发送数据,cookie 发送正常。 我无法准确检查发生了什么,因为连接是通过 SSL 的。我只检查响应。

【问题讨论】:

    标签: java cookies post httpurlconnection


    【解决方案1】:

    根据URLConnectionjavadoc:

    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'] 或类似的东西..)。
    猜你喜欢
    • 2012-12-04
    • 2015-12-09
    • 1970-01-01
    • 2020-11-27
    • 2012-07-30
    • 2016-12-02
    • 2019-04-07
    • 2019-08-26
    • 2016-12-06
    相关资源
    最近更新 更多