栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java后台调用接口(json转string)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java后台调用接口(json转string)

参数

后台调用
String url = "http://localhost:19091/api/largescreen/updateSocket";
        JSONObject jsonObject = new JSONObject();
        JSONObject json = new JSONObject();
        JSONObject json1 = new JSONObject();
        JSONObject json2 = new JSONObject();
        JSONObject json3 = new JSONObject();
        JSONObject json4 = new JSONObject();
        JSONObject json5 = new JSONObject();
        jsonObject.put("userId","1");
        jsonObject.put("groupId","3");
        jsonObject.put("msgType","TALK");
        json.put("alarmStatistics",json1);
        json.put("lineData",json2);
        json.put("alarmListMap",json3);
        json.put("alarmListLimit",json4);
        json.put("streetInfor",json5);
        String msg = json.toJSONString();

        jsonObject.put("msg",msg);
        String sendData = jsonObject.toJSONString();
        httpUtils.httpPost(sendData,url);
接口(参数体前面加@RequestBody 变json)
@RequestMapping("/updateSocket")
    @ResponseBody
    public void dealMsg(@RequestBody NettyMsgDto nettyMsgDto) throws Exception {
参数体类
public class NettyMsgDto {
    //消息类型
    private String msgType;
    //活动id
    private String groupId;
    //用户id
    private String userId;
    //消息内容
    private String msg;

}
接口调用方法
public String httpPost(String sendData, String url) {
        if (!hasInit) {
            init();
        }

        String result = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(sendData, "UTF-8"));
            httpPost.setConfig(requestConfig);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity httpEntity = response.getEntity();
                if (httpEntity != null) {
                    InputStream stream = httpEntity.getContent();
                    String resData = IOUtils.toString(stream, "UTF-8");
                    LOGGER.info("res data--->:{}", resData);
                    result = resData;
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            LOGGER.error("http错误:{}", e);
        }
        return result;
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/592165.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号