java中什么方法可以在微信服务器上面把图片下载到本地服务器并保存(知道微信服务器上面图片的链接)
1条回答 默认 最新
- VICTOR_fusheng 2019-11-29 17:05关注
根据图片链接,转成byte存入数据库,数据库格式为Blob
public static byte[] image2Base64(String imageUrl){ URL url = null; InputStream is = null; ByteArrayOutputStream outputStream = null; HttpURLConnection connection = null; try { url = new URL(imageUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.connect(); is = connection.getInputStream(); outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1){ outputStream.write(buffer, 0,len); } return outputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally{ if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(connection != null) { connection.disconnect(); } } return null; }
/** * * @param imageUrl 图片地址 * @param path 文件下载目录 */ public static void downloadImage(String imageUrl, String path) { URL url = null; InputStream is = null; OutputStream outputStream = null; HttpURLConnection connection = null; try { url = new URL(imageUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.connect(); is = connection.getInputStream(); String suffix = imageUrl.substring(imageUrl.lastIndexOf(".")); File directory = new File(path); if (!directory.exists()){ directory.mkdirs(); } if (!directory.isDirectory()){ throw new RuntimeException("所传的不是目录地址"); } File file = new File(directory,UUID.randomUUID().toString() + suffix); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } }
解决 无用评论 打赏 举报
悬赏问题
- ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
- ¥15 数据可视化Python
- ¥15 要给毕业设计添加扫码登录的功能!!有偿
- ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
- ¥15 微信公众号自制会员卡没有收款渠道啊
- ¥15 stable diffusion
- ¥100 Jenkins自动化部署—悬赏100元
- ¥15 关于#python#的问题:求帮写python代码
- ¥20 MATLAB画图图形出现上下震荡的线条
- ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘