0
点赞
收藏
分享

微信扫一扫

restTemplate 调用第三方接口获取json数据

盖码范 2022-08-17 阅读 54


什么是RestTemplate

RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具,它提供了常见的REST请求方案的模版,例如 GET 请求、POST 请求、PUT 请求、DELETE 请求以及一些通用的请求执行方法 exchange 以及 execute。RestTemplate 继承自 InterceptingHttpAccessor 并且实现了 RestOperations 接口,其中 RestOperations 接口定义了基本的 RESTful 操作,这些操作在 RestTemplate 中都得到了实现。接下来我们就来看看这些操作方法的使用。

第一步 ,首先导入依赖 RestTemplate的方式来调用别人的API,将数据转化为json 格式,引入了fastjson


<!--引入了fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>

<!--restTemplate httpclient 相关依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

第二步,编写RestTemlateConfig,配置好相关信息

restTemplate 调用第三方接口获取json数据_spring

package com.chx.disService.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}


}

第三步,在controller包中 编写controller,调用第三方的API,实现get请求和post请求 这个是别人的

 

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class SpringRestTemplateController {
@Autowired
private RestTemplate restTemplate;
/***********HTTP GET method*************/
@GetMapping("/testGetApi")
public String getJson(){
String url="http://localhost:8089/o2o/getshopbyid?shopId=19";
//String json =restTemplate.getForObject(url,Object.class);
ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
String json = results.getBody();
return json;
}

/**********HTTP POST method**************/
@PostMapping(value = "/testPost")
public Object postJson(@RequestBody JSONObject param) {
System.out.println(param.toJSONString());
param.put("action", "post");
param.put("username", "tester");
param.put("pwd", "123456748");
return param;
}

@PostMapping(value = "/testPostApi")
public Object testPost() {
String url = "http://localhost:8081/girl/testPost";
JSONObject postData = new JSONObject();
postData.put("descp", "request for post");
JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
return json;
}
}

下面这个是自己写的post方式请求第三方API接口

@PostMapping(value = "/test3PostApi")
public Object testPost1(@RequestBody JSONObject param) throws URISyntaxException {
RestTemplate restTemplate = new RestTemplate();
//这里的url是自己项目的接口
URI uri = new URI("http://vs.clouddkj.com/YDS/doPost");
// String appCode = "52cc0ea3aaf24eb7a1250f327fea9f25";
HttpHeaders headers = new HttpHeaders();
//设置请求头为json格式
headers.set("Accept-Charset", "UTF-8");
headers.set("Content-Type", "application/json; charset=utf-8");
// headers.add("Authorization", "APPCODE " + appCode);
//添加参数,因为HttpEntity里面的参数是MultiValueMap类型的,所以使用这个map集合
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("id","7");
map.add("beginDate", "2020-04-26 10:00:00");
map.add("endDate", "2021-04-21 10:00:00");
map.add("version", "3");
map.add("sign", "e4");



//添加请求的实体类,这里第一个参数是要发送的参数,第二个参数是请求头里的数据
HttpEntity<Object> requestEntity = new HttpEntity<>(map, headers);


//第一种方法
String s = restTemplate.postForObject(uri, requestEntity, String.class);
JSONObject jsonObject = JSON.parseObject(s);
System.out.println(jsonObject);
/*
//第二种方法
//发送post请求
ResponseEntity<String> exchange = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class);
//将返回的值转换为json数据
JSONObject jsonObject = JSON.parseObject(exchange.getBody());
System.out.println(jsonObject);
*/
//封装接口数据到数据库
List<Map<String, String>> resultList = (List<Map<String, String>>) jsonObject.get("Result");
for (Map<String, String> obj : resultList) {
System.out.println(obj);
//在这里把你获取到的数据封装到你需要的实体类中,调用你需要的方法即可存入数据库
//......
}
return jsonObject;
}

上面里面的post里面的参数可以不写主要是里面的设置的map里面的值

测试成功

restTemplate 调用第三方接口获取json数据_网络_02


也可以用swagger测试也可以成功

这里有些人可能就有些疑问,为什么参数是要用

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();

这种map集合,因为在

HttpEntity<Object> requestEntity = new HttpEntity<Object>(map, headers);

这里面使用的参数类型就是以上map,源码为证:不管你调用的是哪种构造方法,到最后都是调用第四种构造方法,参数就是MultiValueMap类型。

亲测HashMap不行!!!
这里再多说一下MultiValueMap这个接口,是一个键对应多个值,value是一个list集合,Spring的内部实现是LinkedMultiValueMap;

LinkedMultiValueMap默认是按照你插入的顺序进行排序。
参考
​RestTemplate 调用第三方接口


举报

相关推荐

0 条评论