springboot 2.0 整合 RestTemplate

Posted 情陌人灬已不在

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 2.0 整合 RestTemplate相关的知识,希望对你有一定的参考价值。

首先导入springboot 的 web 包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

restTemplateBuilder的方式被废弃,就推荐使用。

@Configuration
public class AppConfig
{
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) 
    {
        return restTemplateBuilder
           .setConnectTimeout(...)
           .setReadTimeout(...)
           .build();
    }
}

在启动类同包下创建RestTemplate.java类:

2.0之后的方法,可以通过SimpleClientHttpRequestFactory来设置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangcanfeng
 * @time 2019/3/6
 * @function 远程调用rest接口客户端注册
 **/
@Configuration
public class RestTemplateAutoConfiguration {
     //连接超时时间
    @Value("${rest.connection.timeout}")
    private Integer connectionTimeout;
     // 信息读取超时时间
    @Value("${rest.read.timeout}")
    private Integer readTimeout;

    /**
     * 功能描述:注册restTemplate服务
     *
     * @param
     * @author wangcanfeng
     * @time 2019/3/6 20:26
     * @since v1.0
     **/

    @Bean
    public RestTemplate registerTemplate() {
        RestTemplate restTemplate = new RestTemplate(getFactory());
         //这个地方需要配置消息转换器,不然收到消息后转换会出现异常
        restTemplate.setMessageConverters(getConverts());
        return restTemplate;
    }


    /**
     * 功能描述: 初始化请求工厂
     *
     * @param
     * @author wangcanfeng
     * @time 2019/3/6 20:27
     * @since v1.0
     **/
    private SimpleClientHttpRequestFactory getFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(connectionTimeout);
        factory.setReadTimeout(readTimeout);
        return factory;
    }

    /**
     * 功能描述:  设置数据转换器,我再这里只设置了String转换器
     *
     * @param
     * @author wangcanfeng
     * @time 2019/3/6 20:32
     * @since v1.0
     **/
    private List<HttpMessageConverter<?>> getConverts() {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        // String转换器
        StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
        List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
            //配置text/plain和text/html类型的数据都转成String
            add(new MediaType("text", "plain", Charset.forName("UTF-8")));
            add(MediaType.TEXT_HTML);
        }};
        stringConvert.setSupportedMediaTypes(stringMediaTypes);
        messageConverters.add(stringConvert);
        return messageConverters;
    }
}

然后在Service类中注入使用即可

@Service
public class demoService {
 
    @Autowired
    private RestTemplate restTemplate;
 
    public String get(Integer id){
        return restTemplate.getForObject("http://localhost:8080/user?userId=id",String.class);
    }
}

RestTemplate定义了36个与REST资源交互的方法,其中的大多数都对应于HTTP的方法。 
其实,这里面只有11个独立的方法,其中有十个有三种重载形式,而第十一个则重载了六次,这样一共形成了36个方法。

  • delete() 在特定的URL上对资源执行HTTP DELETE操作
  • exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  • execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  • getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  • getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  • postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  • postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  • headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  • optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  • postForLocation() POST 数据到一个URL,返回新创建资源的URL
  • put() PUT 资源到特定的URL

getForEntity

get请求就和正常在浏览器url上发送请求一样

下面是有参数的get请求

    @GetMapping("getForEntity/{id}")
    public User getById(@PathVariable(name = "id") String id) {
        ResponseEntity<User> response = restTemplate.getForEntity("http://localhost/get/{id}", User.class, id);
        User user = response.getBody();
        return user;
    }

getForObject

getForObject 和 getForEntity 用法几乎相同,指示返回值返回的是 响应体,省去了我们 再去 getBody() 

    @GetMapping("getForObject/{id}")
    public User getById(@PathVariable(name = "id") String id) {
        User user = restTemplate.getForObject("http://localhost/get/{id}", User.class, id);
        return user;
    }

postForEntity

    @RequestMapping("saveUser")
    public String save(User user) {
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost/save", user, String.class);
        String body = response.getBody();
        return body;
    }

postForObject

用法与 getForObject 一样

如果遇到 postForObject 方法在 Controller 接受不到参数问题 请参考的的另一篇博客 : 

https://www.cnblogs.com/deityjian/p/12513377.html

exchange

@PostMapping("demo")
public void demo(Integer id, String name){
 
        HttpHeaders headers = new HttpHeaders();//header参数
        headers.add("authorization",Auth);
        headers.setContentType(MediaType.APPLICATION_JSON);
 
        JSONObject obj = new JSONObject();//放入body中的json参数
        obj.put("userId", id);
        obj.put("name", name);
 
        HttpEntity<JSONObject> request = new HttpEntity<>(content,headers); //组装
  
        ResponseEntity<String> response = template.exchange("http://localhost:8080/demo",HttpMethod.POST,request,String.class);
    }

springboot2.0 RestTemplate,get,post,put,delete设置请求header示例

package smartt.styy.auth.util;
import java.net.URI;
import java.nio.charset.Charset;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
 
 
@Component
public class ExternalCallUtils {
    
    //统一,认证服务接口调用post
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static String restRequest(Object reqParam,Boolean needHeader,String Headers,HttpMethod method, String url) throws Exception{
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            //设置token值
            if(needHeader) {
                headers.add("Authorization", Headers);
            }
            RequestEntity request = null ;
            if(null != reqParam) {
                request = new RequestEntity(reqParam,headers, method, new URI(url));
            }else {
                request = new RequestEntity(headers, method, new URI(url));
            }
            
            RestTemplate rest =new RestTemplate();
            ResponseEntity<String> resp =  rest.exchange(request, new ParameterizedTypeReference<String>(){});
            System.out.println("resp status:"+resp.getStatusCode());
            if(resp.getStatusCode()!=null && resp.getStatusCodeValue() ==200) {
                return resp.getBody();
            }
        } catch (Exception e) {
            throw new Exception("认证服务失败!");
        }
        return null;
    }
    
    
    //put delete ,obj为请求实体,转json
    public static <T> T restPutRequest(Object obj, String url,String token, HttpMethod method, Class<T> bodyType) throws Exception{
 
        
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        //提供json转化功能
        //ObjectMapper mapper = new ObjectMapper();
        
        if(!StringUtils.isEmpty(token)){
            headers.add("Authorization", token);
        }
        
 
        String jsonStr = JSONObject.toJSONString(obj);
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(jsonStr, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity = restTemplate.exchange(url, method, entity, bodyType);
        return resultEntity.getBody();
    }
    
    
    
    //get
    public static <T> T restGetRequest(Class<T> bodyType,String url,String token, HttpMethod method) throws Exception{
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        //提供json转化功能
        //ObjectMapper mapper = new ObjectMapper();
        
        if(!StringUtils.isEmpty(token)){
            headers.add("Authorization", token);
        }
        
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<T> resultEntity =  restTemplate.exchange(url,method,entity,bodyType);
        return resultEntity.getBody();
        
    }
    
    
}

以上是关于springboot 2.0 整合 RestTemplate的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 2.0 整合shiro1.4 手记

springboot 2.0 整合 同时支持jsp+html跳转

Kafka在SpringBoot 2.0中的整合

SpringBoot 2.0 + Apache Dubbo 2.7.3 最新版整合方案

spring boot 2.0 整合 elasticsearch NoNodeAvailableException

SpingBoot:整合Elasticsearch7.2.0