先寫一個發送請求的一個工具類BackEndHttpRequest
package com.bs.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class BackEndHttpRequest { /** * 向指定的URL發送GET方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式 * @return 遠程資源的響應結果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader bufferedReader = null; try { //1、讀取初始URL String urlNameString = url + "?" + param; //2、將url轉變為URL類對象 URL realUrl = new URL(urlNameString); //3、打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); //4、設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); //connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); //5、建立實際的連接 connection.connect(); //獲取所有響應頭字段 Map<String, List<String>> map = connection.getHeaderFields(); //遍歷所有的響應頭字段 for(String key : map.keySet()) { System.out.println(key + "---->" + map.get(key)); } //6、定義BufferedReader輸入流來讀取URL的響應內容 ,UTF-8是后續自己加的設置編碼格式,也可以去掉這個參數 bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line = ""; while(null != (line = bufferedReader.readLine())) { result += line; } // int tmp; // while((tmp = bufferedReader.read()) != -1){ // result += (char)tmp; // } }catch (Exception e) { // TODO: handle exception System.out.println("發送GET請求出現異常!!!" + e); e.printStackTrace(); }finally { //使用finally塊來關閉輸入流 try { if(null != bufferedReader) { bufferedReader.close(); } }catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return result; } /** * 向指定的URL發送POST方法的請求 * @param url 發送請求的URL * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式 * @return 遠程資源的響應結果 */ public static String sendPost(String url, String param) { String result = ""; BufferedReader bufferedReader = null; PrintWriter out = null; try { //1、2、讀取並將url轉變為URL類對象 URL realUrl = new URL(url); //3、打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); //4、設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 connection.setDoInput(true); connection.setDoOutput(true); //5、建立實際的連接 //connection.connect(); //獲取URLConnection對象對應的輸出流 out = new PrintWriter(connection.getOutputStream()); //發送請求參數 out.print(param); //flush輸出流的緩沖 out.flush(); // //6、定義BufferedReader輸入流來讀取URL的響應內容 bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line; while(null != (line = bufferedReader.readLine())) { result += line; } }catch (Exception e) { // TODO: handle exception System.out.println("發送POST請求出現異常!!!" + e); e.printStackTrace(); }finally { //使用finally塊來關閉輸出流、輸入流 try { if(null != out) { out.close(); } if(null != bufferedReader) { bufferedReader.close(); } }catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } return result; } }
測試:
package com.bs.utils; import java.util.Timer; public class Test { public static void main(String[] args) { //發送 GET 請求 String str1=BackEndHttpRequest.sendGet("http://localhost:8080/showWaterregion", "page=1&rows=5®ionID=4"); System.out.println(str1); //發送 POST 請求 String str2=BackEndHttpRequest.sendPost("http://localhost:8080/waterregion/flow/year", "type=1®ionID=2");
System.out.println(str2);
} }
postman請求數據
get請求的結果此處略;
post請求的結果:
進行解析請求回的json數據:
依賴jar包:
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency>
測試:
package com.bs.utils; import java.util.Timer; import org.json.JSONArray; import org.json.JSONObject; public class Test { public static void main(String[] args) { //發送 GET 請求 String str1=BackEndHttpRequest.sendGet("http://localhost:8080/showWaterregion", "page=1&rows=5®ionID=4"); System.out.println(str1); //發送 POST 請求 String str2=BackEndHttpRequest.sendPost("http://localhost:8080/waterregion/flow/year", "type=1®ionID=2"); System.out.println("get請求json數據-----------------"+str1); JSONObject getjson = new JSONObject(str1); //創建json對象(Json數據) System.out.println(getjson.get("total")); JSONArray getarray = getjson.getJSONArray("rows"); //獲取json中的數組(數組名) for (int i = 0; i < getarray.length(); i++) { //遍歷數組 JSONObject sonObject = getarray.getJSONObject(i); //獲得數組中的第一個對象 System.out.println(sonObject.get("id")); //根據字段名獲得對象的每一個屬性字段 System.out.println(sonObject.get("name")); System.out.println(sonObject.get("readtime")); } System.out.println("post請求json數據-----------------"+str2); JSONObject json = new JSONObject(str2); System.out.println(json.get("status")); System.out.println(json.get("msg")); JSONArray jsonArray = json.getJSONArray("data"); System.out.println(jsonArray); for (int i = 0; i < jsonArray.length(); i++) { JSONObject sonObject = jsonArray.getJSONObject(i); String s = (String) sonObject.get("time"); Double bigDecimal = (Double) sonObject.get("flow"); System.out.println(s); System.out.println(bigDecimal); } } }