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

 

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

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
</dependency>

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<String> requestEntity = new HttpEntity<String>(json.toString(), headers);
        //  执行HTTP请求
        ResponseEntity<String> 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、运行情况

  • 7
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值