Java HttpURLConnection - 带 Cookie 的 POST
我正在尝试发送带有 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。如果我只做: conn.connect();并且不发送数据,cookie 发送正常。 我无法准确检查发生了什么,因为连接是通过 SSL 进行的。我只检查回复。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据
URLConnection
javadoc:您是否确认在上面的测试用例中请求完全到达了服务器?我看到您在
getOutputStream()
之后调用了connect()
并注释掉了。如果您在调用getOutputStream()
之前取消注释并向上移动,会发生什么情况?According to the
URLConnection
javadoc: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()
aftergetOutputStream()
and commented-out besides. What happens if you uncomment it and move up before the call togetOutputStream()
?