RestTemplateForBank.java 2.33 KB
package com.yohoufo.user.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Configuration
public class RestTemplateForBank {
    private Logger logger = LoggerFactory.getLogger(RestTemplateForBank.class);

    /**
     * 定义一个500毫秒超时的RestTemplate,调用银联接口用
     * @return
     */
    @Bean
    public RestTemplate authorizeBankRestTemplate(){
       /* ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
                int statusCode = getHttpStatusResponseCode(clientHttpResponse);
                if(statusCode==200){
                    return false;
                }
                return true;
            }

            @Override
            public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
                int responseCode = getHttpStatusResponseCode(clientHttpResponse);
                logger.error("CustomRestTemplateConfig handleError responseCode {},response {}",responseCode,clientHttpResponse);

            }

            protected int getHttpStatusResponseCode(ClientHttpResponse response) throws IOException {
                try {
                    return response.getStatusCode().value();
                }
                catch (IllegalArgumentException ex) {
                    return 400;
                }
            }
        };*/


        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(500);
        httpRequestFactory.setConnectTimeout(500);
        httpRequestFactory.setReadTimeout(500);

        RestTemplate restTemplate= new RestTemplate(httpRequestFactory);
        //restTemplate.setErrorHandler(responseErrorHandler);
        return restTemplate;
    }
}