开发者

Java HttpURLConnection - POST with Cookie

I´m trying to send a post request with cookies. This is the code:

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

The problem is the request is sent without the cookies. If I only make: conn.connect(); and don´t send data, the cookies are sent OK. I can´t ch开发者_运维技巧eck exactly what is happening, because the connection is thorugh SSL. I only check the response.


According to the 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

Have you confirmed that in your test case above the request is getting to the server at all? I see you have the call to connect() after getOutputStream() and commented-out besides. What happens if you uncomment it and move up before the call to getOutputStream() ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜