我正在尝试使用HttpsUrlConnection向URL发送HTTP POST请求。这是我想要做的:
URL requestedUrl = null;
HttpURLConnection urlConnection = null;
try {
requestedUrl = new URL("https://www.test.local/login/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
urlConnection = (HttpsURLConnection) requestedUrl.openConnection();
try {
urlConnection.setRequestMethod("POST");
} catch (ProtocolException e1) {
e1.printStackTrace();
}
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(1500);
try {
urlConnection.connect();
} catch (IOException e) {
e.printStackTrace();
}
调试时我看到RequestMethod仍然是GET,任何想法为什么?
提前致谢。
答案 0 :(得分:3)
使用给定的代码,您无法在网络跟踪中看到任何请求。
在给定的代码段中,您只能通过urlConnection.connect()
打开连接,但不会执行与urlConnection.getContent()
类似的实际请求。仅connect()
方法不执行请求。
使用以下内容替换上一个try-catch块应发送POST请求:
try {
urlConnection.connect(); // open the connection
urlConnection.getContent(); // send prepared request
} catch (IOException e) {
e.printStackTrace();
}