RestTemplate的配置和使用

配置

/**
 * resttemplate 配置
 */
@Configuration
public class RestTemplateConfig {

	@Bean
	public SimpleClientHttpRequestFactory simpleClientHttpRequestFactory() {

		SimpleClientHttpRequestFactory facotry = new SimpleClientHttpRequestFactory();
		/*10s*/
		facotry.setReadTimeout(10000);
		/*30s*/
		facotry.setConnectTimeout(30000);
		return facotry;
	}

	@Bean(name = "restTemplate")
	public RestTemplate restTemplate(SimpleClientHttpRequestFactory factory) {
		RestTemplate restTemplate = new RestTemplate(factory);
		restTemplate.setErrorHandler(new RestTemplateErrorHandler());
		return restTemplate;
	}
}

配置异常处理

/**
 * 定义处理resttemplate的异常
 */
public class RestTemplateErrorHandler implements ResponseErrorHandler {


	@Override
	public boolean hasError(ClientHttpResponse response) throws IOException {
        boolean hasError = false;
        int rawStatusCode = response.getRawStatusCode();
        if (rawStatusCode != 200){
            hasError = true;
        }
        return hasError;

	}

	@Override
	public void handleError(ClientHttpResponse response) throws IOException {
		String body = IOUtils.toString(response.getBody(), "UTF-8");

		String msg = null;
		if(StringUtils.isNotEmpty(body)) {
			JSONObject jsonObj = JSON.parseObject(body);
			Object msgObj = jsonObj.get("errMsg");
			if(msgObj == null) {
				msg = body;
			} else {
				msg = msgObj.toString();
			}
		}

		RestCustomException ex = new RestCustomException(response.getStatusCode(), body, (msg == null ? "" : msg));
		throw ex;
	}
}

 

抛出异常配置

 

public class RestCustomException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	private HttpStatus statusCode;

    private String body;

    public RestCustomException(String msg) {
        super(msg);
    }

    public RestCustomException(HttpStatus statusCode, String body, String msg) {
        super(msg);
        this.statusCode = statusCode;
        this.body = body;
    }

    public HttpStatus getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(HttpStatus statusCode) {
        this.statusCode = statusCode;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值