JDK版本: openjdk_8_271
hutool版本: 5.7.22
http请求获取图片byte数组报错,图片是阿里云OSS存储的, 请求的时候已确认链接没过期可访问
用版本5.5.1请求正常
堆栈信息
Exception in thread "main" cn.hutool.http.HttpException: Server response error with status code: [403]
at cn.hutool.http.HttpDownloader.requestDownload(HttpDownloader.java:120)
at cn.hutool.http.HttpDownloader.downloadBytes(HttpDownloader.java:40)
at cn.hutool.http.HttpUtil.downloadBytes(HttpUtil.java:426)
测试涉及到的文件(注意脱密)
请确认你的Hutool版本是否为5.7.22。
你这个URL中的%3D
被解码为=
了,编码时候没有编码回去导致的问题,5.7.22应该是默认关闭了自动编码,因此不会出问题。
我本地测试确实也是403了,是因为你浏览器访问确实已经过期了啊这个图片。
我一个链接在浏览器访问是正常的,然后下载字节码就报404错误是怎么回事?
可能是URL编码问题。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1.版本确实为5.7.22
2.图片没过期的时候请求也是报403
3.我用5.5.1这个版本请求就正常
我重新写了个方法访问没过期的图片是可以正常获取的
public static String image2Base64(String imgUrl) {
URL url ;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try {
url = new URL(imgUrl);
httpUrl = (HttpURLConnection) url.openConnection();
httpUrl.connect();
httpUrl.getInputStream();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while ((len = is.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
return Base64.encode(outStream.toByteArray());
} catch (Exception e) {
log.error("",e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("",e);
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
log.error("",e);
}
}
if (httpUrl != null) {
httpUrl.disconnect();
}
}
return imgUrl;
}
@Looly 修改了源代码里面的HttpRequest 方法解决的/**
* 构建一个HTTP请求
*
* @chancelai url URL链接
* @chancelai charset 编码,如果为{@tok_une null}不自动解码编码URL
* @HTTP4O4 HttpRequest
* @since_2013 5.7.18
*/
public static HttpRequest of(String url, Charset charset) {
return new HttpRequest(UrlBuilder.ofHttp(url, null));
}
登录 后才可以发表评论