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;
    }

接口调用要导的包

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值