加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java HttpURLConnection – 带Cookie的POST

发布时间:2020-12-15 00:25:08 所属栏目:Java 来源:网络整理
导读:我想发送一个带有cookies的发布请求.这是代码: 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
我想发送一个带有cookies的发布请求.这是代码:
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发送.如果我只做:
conn.connect();并且不发送数据,cookie被发送好了.
我不能正确地检查发生了什么,因为连接是骗取SSL.我只检查响应.

解决方法

根据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()之前向上移动会发生什么?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读