文章目录
项目中遇到一个需求,复制网络文章到自己的编辑器中,要保证排版及图片都差不多,前端大佬拔下了一堆头发终于搞定了大半,唯独图片被加密无法显示~~ 于是该后端出场啦!
HttpURLConnection 下载网络图片
URL url = new URL(imgSrc);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Accept-Encoding", "identity");
String fileName = String.format("web_image_%s.%s", UUID.randomUUID(), "jpg");
if (conn.getResponseCode() != 200) {
log.error("请求获取图片url({})失败,错误码为:{}", imgSrc, conn.getResponseCode());
return "";
}
try (InputStream inputStream = conn.getInputStream();) {
//上传文件流到oss上
String uploadPath = fileName;
upload2OSS(fileName, inputStream );
return uploadPath;
} catch (UnknownServiceException e) {
log.error(e.getMessage());
throw e;
}
上传到OSS
关键代码如下:
private void upload2OSS(String uploadPath, InputStream inputStream) {
// 创建上传Object的Metadata。ObjectMetaData是用户对该object的描述
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(length);
objectMetadata.setCacheControl("no-cache");
objectMetadata.setContentEncoding("utf-8");
objectMetadata.setContentType(getcontentType(null, fileSuffix));// 获取文件类型
objectMetadata.setContentDisposition("attachment;filename=" + fileName);
OSS ossClient = createOssClient("endpoint", "accesKeyId", "secretAccessKey");
ossClient.putObject("bucket", uploadPath, inputStream, objectMetadata);
}
private OSS createOssClient(String endpoint, String accessKeyId, String secretAccessKey) {
ClientBuilderConfiguration config = new ClientBuilderConfiguration();
config.setProtocol(Protocol.HTTPS);
return new OSSClientBuilder().build(endpoint, accessKeyId, secretAccessKey, config);
}
遇到的问题
InputStream.available()为0
在调试过程中,为了查看网络图片是否下载成功,打印了InputStream.available()
发现一直为0,去看了下源码。。。
=_=|| 官方解释,由于网络不稳定等各种复杂因素,无法从流中获取文件大小,所以直接返回0!不带这么玩的~
public int available() throws IOException {
return 0;
}
好吧,此路不通得换一个方式获取文件大小,HttpURLConnection.getContentLength()
完美解决!
Server returned HTTP response code: 400 for URL
下载路径中包含中文,需要对中文部分进行转码!!!
写篇博客记录下,不然又忘记了!