HttpClient二post带json数据的请求与接收

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/uotail/article/details/86182569

目录

 

post发送json请求

接收端

测试


post发送json请求

直接在上一节的基础上在spring boot的启动类上加方法

 @RequestMapping("/testCallBackByHttp")
    public JSONObject testCallBackByHttp() throws Exception {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("name", "wh");//{"name":"wh"}
        paramsMap.put("password", "ale");
        String jsonString = JSONObject.toJSONString(paramsMap);
        System.out.println(jsonString);

        String respHtml = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/callBackFor");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");//表示客户端发送给服务器端的数据格式
        //httpPost.setHeader("Accept", "*/*");这样也ok,只不过服务端返回的数据不一定为json
        httpPost.setHeader("Accept", "application/json");                    //表示服务端接口要返回给客户端的数据格式,
        StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        //System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8"));
        System.out.println(statusCode);//200
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity respEnt = response.getEntity();
            respHtml = EntityUtils.toString(respEnt, "UTF-8");
            System.out.println(respHtml);
            JSONObject jsonObject = JSONObject.parseObject(respHtml);//响应结果
            return jsonObject;
        }
        System.out.println(respHtml);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resp",respHtml);
        return jsonObject;

    }

接收端

   @PostMapping("/callBackFor")
    public JSONObject callBackFor(HttpServletRequest request, @RequestBody String data) {
        /*
         *  String data               不可以接受json字符串,只能接收名为data的参数
         * @RequestBody String data 可以以json字符串的形式接收json字符串
         * @RequestBody JSONObject jsonObject 可以接收json字符串并转化为JSONObject对象
         * */
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {//传递json数据的时候request是没有表单参数的
            String parameterName = parameterNames.nextElement();
            System.out.println(parameterName + "===" + request.getParameter(parameterName));
            //System.out.println(parameterNames.nextElement()+"=="+request.getParameter(parameterNames.nextElement()));
        }
        System.out.println(data);//以{}包含的字符串
        //无论是@RequestBody String data还是@RequestBody JSONObject jsonObject 最后都要转换为后者,因此建议@RequestBody JSONObject jsonObject接收json字符串
        JSONObject jsonObject = JSONObject.parseObject(data);
        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        System.out.println("=====我是回调函数=====");
        for (Map.Entry<String, Object> entry : entries) {
            System.out.println(entry.getKey() + "--" + entry.getValue());
        }
        System.out.println("=====================");
        JSONObject result = new JSONObject();
        result.put("code", 1);
        result.put("msg", "调用成功!");
        return result;
    }

测试

启动springBoot 浏览器上输入
http://127.0.0.1:8080/testCallBackByHttp
页面如下
在这里插入图片描述

控制台打印如下

猜你喜欢

转载自blog.csdn.net/uotail/article/details/86182569