RestTemplate用法-基本认证、JWT Token认证、自动重试、文件上传

RestTemplate用法-基本认证、JWT Token认证、自动重试、文件上传

一、基本认证

	/**
     * @param builder
     * @return
     * @see BasicAuthenticationInterceptor
     * @see {@code RestTemplateBuilder#addClientHttpRequestInitializer(org.springframework.web.client.RestTemplate) }
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(120))
                // 基本认证 密码保存在header里,"用户名:密码"拼接后,使用Base64加密
                // header value值示例"Basic YWtaW46YWRtaW4="
                .basicAuthentication("userName", "password")
                // 或者通过增加请求拦截器的方式实现(二选一)
                // .additionalInterceptors(new BasicAuthenticationInterceptor("userName", "password"))
                .build();
    }

二、JWT Token认证

	/**
     * @param builder
     * @return
     * @see BasicAuthenticationInterceptor
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(120))
                // JWT认证
                // header value值示例"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImZ1bGxOYW1lIjoiU3VwZXIgQWRtaW4iLCJjcmVhdGVkQXQiOiIiLCJyb2xlIjpbImFkbWluIl0sImlhdCI6MTYzMDMwNzAzNywiZXhwIjoxNjMwMzQzMDM3fQ.AQA6RZN_zoFIMMdw0K0lF0Q7xpy6JlygbyMK3nOe5B4"
                .additionalInterceptors((request, body, execution) -> {
                    HttpHeaders headers = request.getHeaders();
                    if (!headers.containsKey(HttpHeaders.AUTHORIZATION)) {
                        // TODO 获取accessToken
                        final String accessToken = "accessToken";
                        headers.setBearerAuth(accessToken);
                    }
                    ClientHttpResponse clientHttpResponse = execution.execute(request, body);
                    return clientHttpResponse;
                })
                .build();
    }

三、请求自动重试

1.pom.xml

        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
            <version>1.3.1</version>
        </dependency>

2.重试代码实现

    /**
     * 结合RetryTemplate重试框架(编程式方式)
     * RetryTemplate重试框声明式注解方式:依赖{@code spring-boot-starter-aop }且重试类必须注入为spring bean
     * @param builder
     * @return
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(120))
                .additionalInterceptors((request, body, execution) -> {
                    // RetryTemplate 1.3之后支持链式写法
                    RetryTemplate retryTemplate = RetryTemplate.builder()
                            .maxAttempts(10)
                            .exponentialBackoff(100, 2, 10000)
                            .retryOn(RestClientException.class)
                            .build();
                    return retryTemplate.execute(context -> execution.execute(request, body));
                })
                .build();
    }

四、文件上传

1. 媒体类型 MediaType.APPLICATION_OCTET_STREAM

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
try (InputStream in = file.getInputStream()) {
    HttpEntity<?> requestEntity = new HttpEntity<>(new InputStreamResource(in), headers);
    final String result = restTemplate.postForObject(uri, requestEntity, String.class);
}

2. 媒体类型 MediaType.MULTIPART_FORM_DATA

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
try (InputStream in = file.getInputStream()) {
    MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("file", new InputStreamResource(in));
    HttpEntity<?> requestEntity = new HttpEntity<>(requestBody, headers);
    final String result = restTemplate.postForObject(uri, requestEntity, String.class);
}

参考:
精讲RestTemplate第9篇-如何通过HTTP Basic Auth认证

Spring Retry重试框架

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JWT(JSON Web Token)是一种用于在不同系统之间安全地传递信息的标准。使用JWT进行认证授权通常涉及以下步骤: 1.用户向应用程序发送其凭据(例如用户名密码)。 2.应用程序使用这些凭据进行身份验证并生成JWT。 3.应用程序将JWT作为响应发送回客户端。 4.客户端将JWT保存在本地(通常是在浏览器的localStorage中)。 5.客户端向应用程序发送请求,该请求包括JWT作为Authorization标头的一部分。 6.应用程序使用JWT来验证请求的有效性。如果JWT有效,则请求被授权。 以下是一个使用Node.js实现JWT认证授权的示例: ```javascript const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); // 登录路由 app.post('/login', (req, res) => { // 获取用户凭据 const { username, password } = req.body; // 在这里进行身份验证 // 创建JWT const token = jwt.sign({ username }, 'secret_key'); // 将JWT发送回客户端 res.json({ token }); }); // 受保护的路由 app.get('/protected', (req, res) => { // 获取Authorization标头 const authHeader = req.headers.authorization; // 如果该标头不存在或不是Bearer格式,则返回401 Unauthorized if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ error: 'Unauthorized' }); } // 从JWT中提取用户名 const token = authHeader.split(' ')[1]; const { username } = jwt.verify(token, 'secret_key'); // 在这里进行授权检查 // 如果通过授权检查,则返回200 OK res.send('You are authorized!'); }); app.listen(3000, () => { console.log('Server started on http://localhost:3000'); }); ``` 在上面的示例中,我们使用jsonwebtoken库来创建和验证JWT。在登录路由中,我们使用jwt.sign()方法创建JWT。在受保护的路由中,我们使用jwt.verify()方法来验证JWT,以确保其有效,并从中提取用户名以进行授权检查。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬山境KL攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值