尽管将POST设置为方法类型,HttpUrlConnection类仍执行GET

时间:2017-08-31 13:13:41

标签: java post https get httpurlconnection

我正在尝试使用具有GET和POST请求处理程序的API。 我正在尝试执行GET请求,如下所示:

HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();

我得到了正确的 Cookie 以及 HTML 响应。

但是现在我尝试在同一个URL上执行POST请求,如下所示:

String postBody = "__RequestVerificationToken=" + __RequestVerificationToken + "&Username=" + userName
            + "&Password=" + passWord;
byte[] postData = postBody.getBytes(StandardCharsets.UTF_8);

HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Length", Integer.toString(postData.length));
httpURLConnection.setUseCaches(false);

/**
 * write the request body as bytes
 */
OutputStream os = httpURLConnection.getOutputStream();
os.write(postBody.getBytes());
os.flush();
os.close();

所有我进入 Cookies HTML Response 与之前在GET请求中收到的内容相同。

有人可以解释一下发生了什么吗?

1 个答案:

答案 0 :(得分:0)

您需要添加httpURLConnection.setDoInput(true);

<!-- language: java -->
String postBody = "__RequestVerificationToken=" + __RequestVerificationToken + "&Username=" + userName
            + "&Password=" + passWord;
byte[] postData = postBody.getBytes(StandardCharsets.UTF_8);

HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Length", Integer.toString(postData.length));
httpURLConnection.setUseCaches(false);

/**
 * write the request body as bytes
 */
OutputStream os = httpURLConnection.getOutputStream();
os.write(postBody.getBytes());
os.flush();
os.close();