1.先看整體關鍵代碼,我將發送請求和接收數據封裝成了 jsonPost(JsonParam jsonParam) 方法。
public static JSONArray jsonPost(JsonParam jsonParam) throws IOException { //對方要求以json格式把請求參數以post的方式傳過去 JSONObject inner = DataDeal.getJSON(jsonParam); System.out.println(inner); // 這里參數是包裝了兩層的。不是.net不用包兩層。看對方需求 //JSONObject param = new JSONObject(); //param.put("data", inner.toString()); String url = "http://10.55.88.66:8080/data-service/back"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json"); //httpPost.setEntity(new StringEntity(inner.toString())); httpPost.setEntity(new StringEntity(inner.toString(),"UTF-8")); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "utf-8"); JSONArray resJsonArray= JSONArray.parseArray(result); return resJsonArray; }
2.上面標題一中方法的入參為JsonParam jsonParam,不用在意,只是簡單封裝了一點數據,通過實體類傳進來了。
3.重頭戲來了,真正傳給接口的入參是標題一代碼中JSONObject 類型的inner,而inner的賦值,這里我是從我封裝的另一個getJSON(jsonParam)方法中返回的,下面是getJSON(jsonParam)方法的代碼。
public static JSONObject getJSON(JsonParam jsonParam){ //對方要求以json格式把請求參數以post的方式傳過去 JSONObject inner = new JSONObject(); inner.put("dataSource", "pipeproject"); inner.put("limitLower", "0"); inner.put("limitUpper", "80"); inner.put("queryType", jsonParam.getQueryType()); inner.put("returnFields", jsonParam.getReturnFields()); inner.put("filter",jsonParam.getFilter()); inner.put("distinct",jsonParam.getDistinct()); return inner; }
我們可以看到,inner存入的都是鍵值對,具體數據和類型就要看具體要求了。
4.又來一個重頭戲,重頭戲不嫌多。返回類型!這也是要看具體情況,我這里的需求大多數都是返回的JSONArray,當然還有可能是JSONObject,等等,其他的留待后面研究與總結。
5.獲取的JSONArray怎么處理呢?請看下面代碼
List<String> strList = new ArrayList<>(); for(Object obj:jsonArray){ String resString = JSONObject.parseObjec(obj.toString()).getString("name"); strList.add(resString); }
這段代碼的意思就是遍歷返回的jsonArray,在每個jsonObject中查找key值為“name”的鍵值對,將value值添加到了strList中。