[英]Java HttpURLConnection - POST with Cookie
我正在嘗試發送帶有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。 我只檢查回復。
根據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()
並且注釋掉了。 如果取消注釋並在調用getOutputStream()
之前向上移動會發生什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.