SpringBoot使用RestTemplate


設置pom引用

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itstudy</groupId>
    <artifactId>demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <name>demo</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

 

2.增加配置類

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;
import org.springframework.http.converter.StringHttpMessageConverter;
import java.nio.charset.Charset;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        RestTemplate restTemplate= new RestTemplate(factory);
        // 支持中文編碼
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;

    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//單位為ms
        factory.setConnectTimeout(5000);//單位為ms
        return factory;
    }
}

3.在service中使用

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class RestTestService {

    @Autowired
    private RestTemplate restTemplate;

    public void test(){

        String paras = "data";
        String url="http://127.0.0.1";

        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        JSONObject jsonObj = JSONObject.parseObject(paras);
        HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
        String result = restTemplate.postForObject(url, formEntity, String.class);
    }

    public void testExchage(){
        
        String url="";
        
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));

        Map<String,String> postData = new HashMap<String,String>();
        postData.put("param1","123");
        postData.put("param2","abc");

        //發送json字符串
        String content = JSON.toJSONString(postData);
        
        HttpEntity<String> httpEntity = new HttpEntity<String>(content, httpHeaders);
        
        try {
        
            ResponseEntity<String> responseEntity =
                    restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
                    
            Map<String,String> mapResponse = JSON.parseObject(responseEntity.getBody(),HashMap.class);

        }catch (Exception ex){
            //進行錯誤處理
        }
    }

    public void testExchage2(){
        
        String url="";
        
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
        
        //參數放入一個map中,restTemplate不能用hashMap
        MultiValueMap<String,String> param = new LinkedMultiValueMap<String, String>();
        //將請求參數放入map中
        param.add("param1","abc");
        param.add("param2","123");
        
        //將參數和header組成一個請求
        HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(param,headers);

        try {
            ResponseEntity<String> responseEntity =
                    restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);    
        
            //responseEntity.getBody()進行其它處理

        }catch (Exception ex){
            //進行錯誤處理
        }
    }
}

4.應用啟動

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(App.class);
        //關閉banner
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }

}

另外注意RestTemplate默認 如果返回狀態不是200則會報錯,因此這個要進行捕獲

/判斷接口返回是否為200
    public static Boolean ping(){
        String url = domain + "/it/ping";
        try{
            ResponseEntity<String> responseEntity = template.getForEntity(url,String.class);
            HttpStatus status = responseEntity.getStatusCode();//獲取返回狀態
            return status.is2xxSuccessful();//判斷狀態碼是否為2開頭的
        }catch(Exception e){
            return false; //502 ,500是不能正常返回結果的,需要catch住,返回一個false
        }
    }

或者進行自定義處理

import java.io.IOException;

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

@Configuration
public class RestTemplateConfig {
    
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) throws Exception {
        RestTemplate restTemplate = new RestTemplate(factory);
        ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                return true;
            }
            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

            }
        };
        restTemplate.setErrorHandler(responseErrorHandler);
        return restTemplate;
    }
    
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //讀取超時5秒
        factory.setReadTimeout(5000);
        //連接超時15秒
        factory.setConnectTimeout(15000);
        return factory;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM