1.先看整体关键代码,我将发送请求和接收数据封装成了 jsonPost(JsonParam jsonParam) 方法。
public static JSONArray jsonPost(JsonParam jsonParam) throwsIOException {//对方要求以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= newHttpPost(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);returnresJsonArray;
}
2.上面标题一中方法的入参为JsonParam jsonParam,不用在意,只是简单封装了一点数据,通过实体类传进来了。
3.重头戏来了,真正传给接口的入参是标题一代码中JSONObject 类型的inner,而inner的赋值,这里我是从我封装的另一个getJSON(jsonParam)方法中返回的,下面是getJSON(jsonParam)方法的代码。
public staticJSONObject getJSON(JsonParam jsonParam){//对方要求以json格式把请求参数以post的方式传过去
JSONObject inner = newJSONObject();
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());returninner;
}
我们可以看到,inner存入的都是键值对,具体数据和类型就要看具体要求了。
4.又来一个重头戏,重头戏不嫌多。返回类型!这也是要看具体情况,我这里的需求大多数都是返回的JSONArray,当然还有可能是JSONObject,等等,其他的留待后面研究与总结。
5.获取的JSONArray怎么处理呢?请看下面代码
List strList = new ArrayList<>();for(Object obj:jsonArray){
String resString= JSONObject.parseObjec(obj.toString()).getString("name");
strList.add(resString);
}
这段代码的意思就是遍历返回的jsonArray,在每个jsonObject中查找key值为“name”的键值对,将value值添加到了strList中。
该博客主要介绍Java处理App发过来的数据项目。将发送请求和接收数据封装成jsonPost方法,详细展示其代码实现。还给出getJSON方法为接口入参赋值。同时提到返回类型多样,以JSONArray为例展示了处理返回结果的代码。
2万+

被折叠的 条评论
为什么被折叠?



