2017-08-31 182 views
0

我试图找到一个既有GET请求处理又有POST请求处理程序的API。 虽然我试图执行GET请求,这是如下:尽管将POST设置为方法类型,HttpUrlConnection类仍然执行GET

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

我得到适当的饼干以及HTML响应。

但现在我尝试在同一网址进行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(); 

所有我在饼干HTML响应得到的是同上什么,我在用GET请求早些时候接受。

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

回答

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(); 
+0

究竟在哪里?在POST通话时? – Vishal

+0

' httpURLConnection.setDoOutput(true); 012URhttpURLConnection.setDoInput(true); ... ' –

+0

感谢您的时间先生,但它仍然没有工作 – Vishal

相关问题