java后端接收其他项目接口传来的数据


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM