spring boot使用restTemplate获取image/jpeg

最近老板想要将公司业务数据进行一个汇总,做一个数据可视化的平台,由于呢公司的业务比较零散,前后四五个平台,我就想着做一个后台统一收集几个平台的数据进行梳理展示,于是用到了restTemplate,其中要获取验证码进行登录,就记录下来。

技术选型:spring boot 2 + vue3

直接使用遇到的问题

由于前后端分离,restTemplate获取数据和前端获取数据属于两个会话请求,这就导致set-Cookie不一致,在前端输入验证码提交后台进行登录操作会失败

解决方案

使用restTemplate获取验证码图片,然后转换成二进制流的形式让前端获取即可解决

代码如下

HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "image/jpeg");
        HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<MultiValueMap<String, Object>>(headers);
        // Resource类写出来,方便参考
        ResponseEntity<org.springframework.core.io.Resource> responseEntity = restTemplate.exchange(PATH+"servlet/xxxx.do(你自己的地址)", HttpMethod.GET, formEntity, org.springframework.core.io.Resource.class);
        String setCookie = responseEntity.getHeaders().get("Set-Cookie").get(0);
        String cookies = setCookie.split(";")[0];
        // 写了一个缓存存储cookies
        CacheCookies cacheCookies = CacheCookies.getCacheCookies();
        cacheCookies.setCookies(cookies);
        InputStream inputStream = null;
        try {
        // 获取响应中的body
            inputStream = responseEntity.getBody().getInputStream();
        // 转换成流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num = inputStream.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = inputStream.read(buffer);
            }
            baos.flush();
            byte[] data = baos.toByteArray();
        // spring boot使用ServletRequestAttributes获取request或者response等
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = requestAttributes.getResponse();
            try {
                response.getOutputStream().write(data);
                response.getOutputStream().flush();
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

如上所示即可获取image,登陆成功后把token写入到请求头即可获取想要的数据。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用第三方库 kaptcha 来生成验证码图片Spring Boot 作为后端提供接口,Vue 作为前端展示验证码图片和发送验证码请求。 首先添加 kaptcha 依赖: ```xml <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> ``` 在 Spring Boot 中配置 kaptcha: ```java @Configuration public class KaptchaConfig { @Bean public Producer kaptchaProducer() { Properties properties = new Properties(); properties.setProperty("kaptcha.border", "no"); properties.setProperty("kaptcha.textproducer.font.color", "black"); properties.setProperty("kaptcha.image.width", "150"); properties.setProperty("kaptcha.image.height", "50"); properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); properties.setProperty("kaptcha.textproducer.char.length", "4"); Config config = new Config(properties); DefaultKaptcha producer = new DefaultKaptcha(); producer.setConfig(config); return producer; } } ``` 然后在 Controller 中提供生成验证码图片的接口: ```java @RestController public class CaptchaController { private final Producer kaptchaProducer; public CaptchaController(Producer kaptchaProducer) { this.kaptchaProducer = kaptchaProducer; } @GetMapping("/captcha.jpg") public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String text = kaptchaProducer.createText(); request.getSession().setAttribute("captcha", text); BufferedImage image = kaptchaProducer.createImage(text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); out.flush(); out.close(); } } ``` 在 Vue 中,可以使用 axios 发送请求获取验证码图片并展示: ```vue <template> <div> <img :src="captchaUrl" @click="refreshCaptcha" /> <input v-model="captcha" /> <button @click="submit">提交</button> </div> </template> <script> import axios from 'axios' export default { data() { return { captcha: '', captchaUrl: '/captcha.jpg' } }, methods: { refreshCaptcha() { this.captchaUrl = '/captcha.jpg?' + Date.now() }, submit() { axios.post('/verifyCaptcha', { captcha: this.captcha }) } } } </script> ``` 在后端提供验证验证码的接口: ```java @PostMapping("/verifyCaptcha") public boolean verifyCaptcha(HttpServletRequest request, @RequestBody Map<String, String> captcha) { String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); if (sessionCaptcha != null && sessionCaptcha.equals(captcha.get("captcha"))) { return true; } return false; } ``` 以上代码只是一个简单的验证码示例,实际项目中还需要进行安全性和用户体验的优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值