Spring之RestTemplate使用-封装Util

在项目开发过程中调用别的服务的接口是经常发生的现象,封装调用工具有助于统一日志打印(追踪调用情况),和统一管理。

注入对象

注意springboot1.0和2.0的超时设置的区别

@Configuration
public class Configeration {
     //    springbot1.0设置超时时间
//	@Bean
//	public RestTemplate restTemplate() {
//		//设置RestTemplate超时时间
//		HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
//		httpRequestFactory.setConnectionRequestTimeout(8000);
//		httpRequestFactory.setConnectTimeout(8000);
//		httpRequestFactory.setReadTimeout(8000);
//		return new RestTemplate(httpRequestFactory);
//	}


    //springboot2.0设置超时时间
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(3000);
        return new RestTemplate(requestFactory);
    }
}

Util

public class RestTemplateUtil {

    public static  JSONObject doGet(String url){
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity responseEntity =restTemplate.getForEntity(url,JSONObject.class);
        serverIsRight(responseEntity);   //判断服务器返回状态码
        return responseEntity.getBody();
    }

    public static JSONObject doPostJson(JSONObject param,String url){
        RestTemplate restTemplate = new RestTemplate();
        //设置提交json格式数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request = new HttpEntity<>(param, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(url,request,JSONObject.class);
        serverIsRight(responseEntity);  //判断服务器返回状态码
        return responseEntity.getBody();
    }

    public static JSONObject doPostForm(String param,String url){
        RestTemplate restTemplate = new RestTemplate();
        //设置表单提交
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap map= new LinkedMultiValueMap<>();
        map.add("userName", param);
        HttpEntity> request = new HttpEntity<>(map, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(url,request,JSONObject.class);
        serverIsRight(responseEntity);  //判断服务器返回状态码
        return responseEntity.getBody();
    }

    public static void serverIsRight(ResponseEntity responseEntity){
        if(responseEntity.getStatusCodeValue()==200){
            System.out.println("服务器请求成功:{}"+responseEntity.getStatusCodeValue());
        }else {
            System.out.println("服务器请求异常:{}"+responseEntity.getStatusCodeValue());
        }
    }

 

你可能感兴趣的:(Spring之RestTemplate使用-封装Util)