1. 程式人生 > >springboot整合RestTemplate呼叫第三方介面

springboot整合RestTemplate呼叫第三方介面

一、首先需要編寫一個RestTemplate配置類,放在入口類所在包或者其子包下:

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;

/**
 * Created by qiaos on 2018/06/28.
 * 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;
    }
}

二、注入介面

//呼叫介面
@Autowired
private RestTemplate restTemplate;

三、方法中具體實現:

import org.springframework.http.*;
//設定請求頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//  封裝引數,千萬不要替換為Map與HashMap,否則引數無法傳遞
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
//新增請求的引數
params.add("hello", "hello");             //必傳
params.add("world", "world");           //選傳
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//  執行HTTP請求
ResponseEntity<String> response = restTemplate.exchange("此處為url地址", HttpMethod.POST, requestEntity, String.class);  //最後的引數需要用String.class  使用其他的會報錯
String body = response.getBody();
if(body != null){
    JSONObject data = (JSONObject) JSON.parse(body);
    //data就是返回的結果
}else{
    
}

-------------------------------------------------------------------------------------------------------------

請求頭的那塊設定:

APPLICATION_FORM_URLENCODED  ==》  application/x-www-form-urlencoded

型別有很多 根據需要修改就ojbk了。