其他分享
首页 > 其他分享> > Sprinboot 整合 RestTemplate 调用 REST 服务

Sprinboot 整合 RestTemplate 调用 REST 服务

作者:互联网

描述

如果需要从应用程序调用远程 REST 服务,可以使用 Spring Framework 的RestTemplate类。由于RestTemplate实例在使用之前经常需要自定义,因此 Spring Boot 不提供任何单个自动配置的RestTemplatebean,但是,它会自动配置 a RestTemplateBuilder,可用于RestTemplate在需要时创建实例。自动配置RestTemplateBuilder确保将 sensibleHttpMessageConverters应用于RestTemplate实例

官网地址: Sprinboot

使用RestTemplate 时候需要自己先自定义实现。

RestTemplate 自定义

有三种主要的RestTemplate自定义方法,具体取决于您希望自定义应用的范围。

为了尽可能缩小任何自定义的范围,请注入自动配置RestTemplateBuilder,然后根据需要调用其方法。每个方法调用都会返回一个新RestTemplateBuilder实例,因此自定义仅影响构建器的这种使用。

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;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//ms 读取时间
        factory.setConnectTimeout(15000);//ms 连接时间
        return factory;
    }
}

可以自己自定义设置时间。

api Doc 文档

RestTemplate

请自行查看文档,调用api。

Rest请求

GET

get请求有3中方式调用:

getForObject:不带参数

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("testRestTemplate")
    public String testRestTemplate() throws IOException {
        String result = restTemplate.getForObject(url + "user/list", String.class);
        return result;
    }

带请求参数:

  Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        String result = restTemplate.getForObject(url + "user/getUser/{id}", String.class, map);
        return new Gson().toJson(result);

可以看到,通过map的方式就能请求带参数,去查询了。

getForEntity:

        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url + "user/getUser/{id}", String.class, map);
        String body = forEntity.getBody();
        return new Gson().toJson(body);

可以看到,当前方法请求,与上一个方法比较,返回值包裹一层,我们需要调用 getBody方法,拿到返回值。

exchange 方式:这个方式可以实现请求带heand 方式,还支持很多方式进行交互

Map<String, Object> param = new HashMap<>();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("key1", "values");
        HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class,param);
        String sttr = response.getBody();

从这里我们就能看出来,当我们请求 get put post 等方式的时候 HttpMethod.GET 只要需要修改这部分就好了。

requestEntity : 可以添加 Header值,这里一般在项目中是请求,授权的部分

null: 这里是传输body的数据的,比如我们添加,修改的时候,这里就可以弄一个对象,tojson 数据交互。

RestTemplateUtil:

package com.example.springbootjpaintegrat.restu;

import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Component
public class RestTemplateUtil {

    private final HttpServletRequest httpServletRequest;
    private final RestTemplate restTemplate;

    public RestTemplateUtil(HttpServletRequest httpServletRequest, RestTemplate restTemplate) {
        this.httpServletRequest = httpServletRequest;
        this.restTemplate = restTemplate;
    }



    /**
     *
     * @param url 请求路径 loge/{orderId}/pay
     * @param method 请求方式
     * @param body body数据 可以为空
     * @param param 请求参数
     * @return
     */
    public String exchange(String url, HttpMethod method, String body, Map<String, Object> param) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "");
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                method,
                new HttpEntity<String>(body, httpHeaders),
                String.class,
                param);
        return response.getBody();
    }


    /**
     * get 请求方式
     * @param url 请求url
     * @return
     */
    public String getForObject(String url) {
        String body = restTemplate.getForObject(url, String.class);
        return body;
    }
}

请求实例:

get getUser/{id}:

    Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        String exchange = restTemplateUtil.exchange(url + "user/getUser/{id}", HttpMethod.GET, null, map);

get getUser:

 Map<String, Object> map = new HashMap<>();
        String exchange = restTemplateUtil.exchange(url + "user/getUser", HttpMethod.GET, null, map);

post: createUser

 Map<String, Object> map = new HashMap<>(0);
    String response = restTemplate.exchange(url +
                        "createUser",
                HttpMethod.POST,
                gson.toJson(new User(1,"11")),
                map);

其他方式同理。项目的代码已经上传到 github上面。

实例代码在github上面需要的请自行拉取:spring-boot-integrate 然后后续会集成更多的模块进去,需要请点个star。后续会集成更多的接口实现,有需要的请保存。

如果这篇文章,有帮助到大家的,请给作者一个一键三连,谢谢

标签:map,String,url,Sprinboot,RestTemplate,REST,restTemplate,new
来源: https://blog.csdn.net/qq_41971087/article/details/120438700