目錄
- 使用GET方法,訪問GET接口,服務端返回405
- 使用GET方法,訪問POST接口,服務端返回405
- 使用POST方法,訪問GET接口,服務端返回405
使用GET方法,訪問GET接口,服務端返回405
發生場景:
復制的POST請求代碼,手動修改為GET,沒有修改徹底,導致錯誤。
錯誤代碼:
public class GET405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";URL url = new URL(defURL);// 打開和URL之間的連接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");//請求get方式con.setDoInput(true);// 默認值為 truecon.setDoOutput(true);//默認值為 false,傳body參數必須寫// 得到請求的輸出流對象OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();// System.out.println("http請求方法:"+con.getRequestMethod());System.out.println("http狀態碼:" + con.getResponseCode());// 獲取服務端響應,通過輸入流來讀取URL的響應InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 關閉連接con.disconnect();// 打印讀到的響應結果System.out.println("運行結束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}
報錯log:
405原因:
con.getOutputStream()
會把原有的GET方法改為POST方法,用POST方法訪問GET接口,就報錯405。看jdk1.8中HttpURLConnection
的getOutpuStream()方法的源碼:
解決辦法:刪掉getOutputStream(),用url傳參。
正確代碼:
public class GET200 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";String body = "username=xiaohu&password=123456";URL url = new URL(defURL+"?"+body);// 打開和URL之間的連接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");//請求get方式// System.out.println("http請求方法:"+con.getRequestMethod());System.out.println("http狀態碼:" + con.getResponseCode());// 獲取服務端響應,通過輸入流來讀取URL的響應InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 關閉連接con.disconnect();// 打印讀到的響應結果System.out.println("運行結束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}
運行結果:
http狀態碼:200
運行結束:{"args": {"password": "123456", "username": "xiaohu"}, "headers": {"Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Host": "httpbin.org", "User-Agent": "Java/1.8.0_221", "X-Amzn-Trace-Id": "Root=1-668a1ba0-278338c97b93d6ca4276c0b0"}, "origin": "113.57.25.151", "url": "https://httpbin.org/get?username=xiaohu&password=123456"
}
使用GET方法,訪問POST接口,服務端返回405
發生場景:接口文檔顯示接口為GET接口,實際上后端人員寫的是POST接口,文檔沒同步。
錯誤代碼:
public class GETtoPOST405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/post";String body="username=xiaohu&password=123456";URL url = new URL(defURL + "?" + body);HttpURLConnection con = (HttpURLConnection) url.openConnection();
// con.setUseCaches(false); // Post請求不能使用緩存con.setRequestMethod("GET");//請求get方式con.setDoInput(true);// 設置是否從HttpURLConnection輸入,默認值為 truecon.setDoOutput(false);// 設置是否使用HttpURLConnection進行輸出,默認值為 falseint code = con.getResponseCode();System.out.println("http狀態碼:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("測試成功");} else {System.out.println("測試失敗:" + code);}// 獲取服務端響應,通過輸入流來讀取URL的響應InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 關閉連接con.disconnect();// 打印讀到的響應結果System.out.println("運行結束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}
報錯log:
http狀態碼:405
測試失敗:405Caused by: java.io.IOException: Server returned HTTP response code: 405 for URL: https://httpbin.org/post?username=xiaohu&password=123456
405原因:不知道后端接口的定義,或者沒有溝通徹底,或者后端開發人員失誤,本應該是GET定義成了POST。應該使用POST方法。
解決方法:使用POST請求。
正確代碼:
public class POSTtoPOST200 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/post";URL url = new URL(defURL);HttpURLConnection con = (HttpURLConnection) url.openConnection();
// con.setUseCaches(false); // Post請求不能使用緩存con.setRequestMethod("POST");//請求POST方式con.setDoOutput(true);// 設置是否使用HttpURLConnection進行輸出,默認值為 falseOutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();int code = con.getResponseCode();System.out.println("http狀態碼:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("測試成功");} else {System.out.println("測試失敗:" + code);}// 獲取服務端響應,通過輸入流來讀取URL的響應InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 關閉連接con.disconnect();// 打印讀到的響應結果System.out.println("運行結束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}
運行結果:
http狀態碼:200
測試成功
運行結束:{"args": {}, "data": "", "files": {}, "form": {"password": "123456", "username": "xiaohu"}, "headers": {"Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Content-Length": "31", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Java/1.8.0_221", "X-Amzn-Trace-Id": "Root=1-668a2091-2a64856935929fab74082ce4"}, "json": null, "origin": "113.57.25.151", "url": "https://httpbin.org/post"
}
使用POST方法,訪問GET接口,服務端返回405
發生場景:代碼失誤,本該寫GET,寫成了POST。
錯誤代碼:
public class POSTtoGET405 {public static void main(String[] args) {try {String defURL = "https://httpbin.org/get";URL url = new URL(defURL);// 打開和URL之間的連接HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("POST");//請求post方式
// con.setUseCaches(false); // Post請求不能使用緩存con.setDoInput(true);// 設置是否從HttpURLConnection輸入,默認值為 truecon.setDoOutput(true);// 設置是否使用HttpURLConnection進行輸出,默認值為 falseOutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");String body = "username=xiaohu&password=123456";writer.write(body);writer.flush();writer.close();int code = con.getResponseCode();System.out.println("http狀態碼:" + code);if (code == HttpURLConnection.HTTP_OK) {System.out.println("測試成功");} else {System.out.println("測試失敗:" + code);}// 獲取服務端響應,通過輸入流來讀取URL的響應InputStream is = con.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));StringBuffer sbf = new StringBuffer();String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();// 關閉連接con.disconnect();// 打印讀到的響應結果System.out.println("運行結束:" + sbf.toString());} catch (Exception e) {e.printStackTrace();}}
}
405原因: 接口只接受GET方法,請求是POST方法。
錯誤場景:后端開發定義失誤,本該是POST接口,寫成了GET。接口沒有測試。
解決辦法:用GET訪問。正確代碼和GET訪問GET一樣。