java 处理app发过来的数据项目_java后端接收其他项目接口传来的数据

该博客主要介绍Java处理App发过来的数据项目。将发送请求和接收数据封装成jsonPost方法,详细展示其代码实现。还给出getJSON方法为接口入参赋值。同时提到返回类型多样,以JSONArray为例展示了处理返回结果的代码。

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中。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值