java发送http请求 cookies,Java HttpURLConnection - POST用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 check 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值