SpringBoot之发送和接收Json格式的HTTP请求

 

1、添加fastjson的依赖到pom.xml中


            com.alibaba
            fastjson
            1.2.45

2、通过@RequestBody 接收json,直接将json的数据注入到了JSONObject里面了

    @ResponseBody
    @RequestMapping(value = "/json/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getByJSON(@RequestBody JSONObject jsonParam) {
        // 直接将json信息打印出来
        //System.out.println(jsonParam.toJSONString());

        // 将获取的json数据封装一层,然后在给返回
        JSONObject result = new JSONObject();
        result.put("msg", "ok");
        result.put("method", "json");
        result.put("data", jsonParam);

        return result.toJSONString();
    }

3、通过resttemplate发送body里面放json的http请求

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Date;
public class TestHttp {
    public static String HttpRestClient(String url, HttpMethod method, JSONObject json) throws IOException {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10*1000);
        requestFactory.setReadTimeout(10*1000);
        RestTemplate client = new RestTemplate(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
        HttpEntity requestEntity = new HttpEntity(json.toString(), headers);
        //  执行HTTP请求
        ResponseEntity response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }

    public static  void  main(String args[]){
        try{
            //api url地址
            String url = "http://127.0.0.1:8090/json/data";
            //post请求
            HttpMethod method =HttpMethod.POST;
            JSONObject json = new JSONObject();
            json.put("name", "wangru");
            json.put("sex", "男");
            json.put("age", "27");
            json.put("address", "Jinan China");
            json.put("time", new Date());
            System.out.print("发送数据:"+json.toString());
            //发送http请求并返回结果
            String result = TestHttp.HttpRestClient(url,method,json);
            System.out.print("接收反馈:"+result);
        }catch (Exception e){
        }
    }
}

4、运行情况

SpringBoot之发送和接收Json格式的HTTP请求_第1张图片

你可能感兴趣的:(后端)