开发者

Java HttpURLConnection - POST with Cookie

开发者 https://www.devze.com 2023-02-21 23:24 出处:网络
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\");

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

精彩评论

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

关注公众号