本文主要是介绍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、运行情况
这篇关于SpringBoot之发送和接收Json格式的HTTP请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!