背景

最近写博客。

觉得自己的博客毫无生机,想加一些图片。

于是在找了一些三方随机图片链接,发现一些问题:

给的些链接不会直接返回图片,
要么是302重定向
要么是返回json

这导致,这个链接无法直接使用在css的background-image: url(xxx)中。

解决思路

后端代理

1、拿到图片真实地址,
2、并将其转换为二进制返回给前端

HttpHelper.java

package com.dshvv.blogserver.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream; @Component
public class HttpHelper {
/*
* 根据url地址返回json
* */
public JSONObject sendGetReturnJson(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 执行请求
CloseableHttpResponse response = httpClient.execute(new HttpGet(url));
// 获取响应体
HttpEntity entity = response.getEntity();
// 获取响应内容
String contentStr = EntityUtils.toString(entity, "utf-8");
// 关闭连接,释放资源
response.close();
httpClient.close();
return JSONObject.parseObject(contentStr);
} /*
* 根据url地址返回二进制
* */
public BufferedInputStream sendGetReturnStream(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 执行请求
CloseableHttpResponse response = httpClient.execute(new HttpGet(url));
// 获取响应体
HttpEntity entity = response.getEntity();
// 获取响应内容
byte[] contentByteArray = EntityUtils.toByteArray(entity);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(contentByteArray);
BufferedInputStream imgStream = new BufferedInputStream(byteInputStream);
// 关闭连接,释放资源
response.close();
httpClient.close();
return imgStream;
}
}

OtherController.js

package com.dshvv.blogserver.controller;

import com.dshvv.blogserver.utils.*;
import io.swagger.annotations.ApiOperation;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse;
import java.io.*; @RequestMapping
@RestController
public class OtherController { @Autowired
private HttpHelper httpHelper; // 随机获取一张二次元图片
@ApiOperation("随机获取一张二次元图片")
@GetMapping(value = {"/img", "/img/{type}"})
public void getImg(HttpServletResponse response, @PathVariable(value = "type", required = false) String type) throws Exception {
String imgApiUrl = "https://api.ixiaowai.cn/api/api.php?return=json"; if (!StringUtils.isBlank(type)) {
if (type.equals("fj")) {
imgApiUrl = "https://api.ixiaowai.cn/gqapi/gqapi.php?return=json";
}
} // 拿到图片的url
String imgUrl = (String) httpHelper.sendGetReturnJson(imgApiUrl).get("imgurl");
System.out.println(imgUrl); // 根据图片url拿到二进制流 并返回前端
BufferedInputStream imgStream = httpHelper.sendGetReturnStream(imgUrl);
OutputStream out = response.getOutputStream(); // 读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = imgStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
out.close();
}
}

遇到的坑

在使用HttpClient时,封装了工具一度存在问题,最后网上排查发现EntityUtils只能使用一次,使用了EntityUtils.toByteArray()方法,上面就不能再使用EntityUtils.toString()。

期间一度准备放弃转听同事@朱杰的使用原生的http请求工具HttpURLConnection,但是大家都说原生的不好,就坚持下来了。

写这篇文章参考了很多,比如参考1参考2

将图片地址转为二进制(博客自定义随机背景图API)的更多相关文章

  1. 如何在CSDN博客自定义栏目中添加“给我写信”

    在"自定义栏目"中添加"连接"(将自己的微博,QQ空间和CSDN博客关联起来)很多人都做过.但是添加"给我写信"这个功能,用的好像不太多.此 ...

  2. 关于hexo博客自定义域名后gitment评论系统登陆出现redirect error返回主页的解决办法

    title: 关于hexo博客自定义域名后gitment评论系统登陆出现redirect error返回主页的解决办法 toc: false date: 2018-04-16 22:57:50 cat ...

  3. 怎样将word中的图片插入到CSDN博客中

    目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...

  4. 博客自定义1-皮肤模板 基于SimpleMemory 添加到顶部小按钮

    周五公司事不是很紧,打算好好弄下自己的博客,这是自己学习和记录分享地方, 首先请记得申请js权限,默认不支持的,博主是已经申请通过后的样子 接着先选择cnblogs一个现有的模板,我这个就是在他的模板 ...

  5. cnblogs博客自定义

    我使用的是博友分享的CCS设计:http://www.cnblogs.com/libaoheng/archive/2012/03/19/2406836.html CSS定制页面风格 /*公用*/ bo ...

  6. 把cnblogs变成简书 - cnblogs博客自定义皮肤css样式

    吐槽 博客园cnblogs作为老牌的IT技术博客类网站,为广大的开发者提供了非常不错的学习交流平台. 虽然博客内容才是重点,但是如果有赏心悦目的页面不更好吗! cnblogs可以更换博客模板,并且提供 ...

  7. IP地址转为二进制,去掉0b补齐八位拼接,再转为十进制

    #!/usr/bin/env python# -*- coding:utf-8 -*- ip = '192.168.0.1' # 转为二进制:# 方法一'''eve = ip.split('.')s ...

  8. 将图片地址转为blob格式的例子

    HTML代码: <div id="forAppend" class="demo"></div> Javascript代码: <sc ...

  9. 【软件学习】如何将Typora中的本地图片上传到博客

    1. 配置方法 下载软件: 点击程序输入博客信息进行配置: 进行偏好设置: 2. 配置中出现的一些问题 解决方法:

  10. 博客中新浪图床 迁移至 阿里云的OSS

    前言 因为之前有个新浪的图床,还挺好用,而且免费,自己博客的图片上传到其上面也挺方便的,但是,前几周吧,突然图片就不能访问了,之前本来是想通过添加 meta 头来解决的,但是发现没有效果.于是就自己搞 ...

随机推荐

  1. C#/.NET/.NET Core技术前沿周刊 | 第 33 期(2025年4.1-4.6)

    前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...

  2. 配置Thymeleaf模板引擎

    1).thymeleaf-starter: 关闭缓存 2).静态资源都放在static文件夹下就可以按照路径直接访问 3).页面放在templates下,直接访问 springboot ,访问项目的时 ...

  3. Windows开机执行bat脚本

    1.编写好bat脚本 2.将脚本复制到: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

  4. HashMap 批量添加

    需要初始化一个常量HashMap,并希望在一行语句中完成.避免像这样的事情: hashMap.put("One", new Integer(1)); // adding value ...

  5. ESP32C3语音AI对话代码分析

    ESP32C3语音AI对话代码分析 代码:基于立创实战派C3例程删改(LCD屏幕显示,触摸和LVGL)和分析 硬件:立创实战派C3 立创官方例程教程链接:第16章 桌面天气助手 | 立创开发板技术文档 ...

  6. SpringBoot静态资源访问--转载

    转载地址:https://www.jianshu.com/p/d40ee98b84b5

  7. FastAPI与Tortoise-ORM开发的神奇之旅

    title: FastAPI与Tortoise-ORM开发的神奇之旅 date: 2025/05/05 00:15:48 updated: 2025/05/05 00:15:48 author: cm ...

  8. 【MOOC】JS脚本|便于复制粘贴中国大学MOOC网站的测试题和选项

    文章目录 运行结果 完整代码 可复用的部分 1. 删除指定Class或Id的DOM元素 2. 在页面上添加按钮并绑定事件.添加css.class 3. 等待页面加载完成,运行异步函数 4. 选中某个D ...

  9. SQL 查询强化 - 数据准备

    最近要搞新的项目了, 我的 BI 报表这块, 我感觉, 可能又要写sql, 对于一些简单的 查询, 表连接我还应付得来, 如果涉及多个表的, 什么子查询嵌套, 自定义函数, 加上控制流...就感觉就不 ...

  10. 实战研究:提升Web应用的安全性

    @charset "UTF-8"; .markdown-body { line-height: 1.75; font-weight: 400; font-size: 15px; o ...