spring boot RestTemplate调用第三方接口
javaRestTemplete 调用第三方接口
·
1、建立配置类
package com.example.mytest.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 RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}
2、逻辑代码中加入依赖注入
@Autowired
private RestTemplate restTemplate;
3、调用逻辑
1)POST调用
@Override
public ResponseEntity<JSONObject> restTempleteApi(String token, List<TStudent> student){
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("token",token);
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
// MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
HttpEntity<List<TStudent>> requestEntity = new HttpEntity<>(student, headers);
ResponseEntity<JSONObject> response = restTemplate.exchange("xxxxxx", HttpMethod.POST, requestEntity, JSONObject.class);
return response;
}
2)get请求
JSONObject result=restTemplate.getForObject("xxxxxxxxxxxxxx",JSONObject.class);
更多推荐
已为社区贡献14条内容
所有评论(0)