[英]Java HttpURLConnection - POST with Cookie
I´m trying to send a post request with cookies. 我正在尝试发送带有cookie的帖子请求。 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. 问题是请求是在没有cookie的情况下发送的。 If I only make: conn.connect(); 如果我只做:conn.connect(); and don´t send data, the cookies are sent OK. 并且不发送数据,cookie被发送好了。 I can´t check exactly what is happening, because the connection is thorugh SSL. 我无法确切地检查发生了什么,因为连接是SSL。 I only check the response. 我只检查回复。
According to the URLConnection
javadoc: 根据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. 我看到你在getOutputStream()
之后调用了connect()
getOutputStream()
并且注释掉了。 What happens if you uncomment it and move up before the call to getOutputStream()
? 如果取消注释并在调用getOutputStream()
之前向上移动会发生什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.