mysql保存和读取微信头像

mysql 保存和读取微信头像


时间:2019年5月5日11:48:44


Util代码:

import lombok.extern.slf4j.Slf4j;
import javax.sql.rowset.serial.SerialBlob;
import java.net.HttpURLConnection;
import java.io.*;
import java.net.URL;
import java.sql.Blob;

/**
  * 根据微信头像的url 获取到数据库对应的Blob对象
  * (https开头的url 可能会有问题)
  * @param headUrl 微信头像的地址
  * @return
  */
@Slf4j
public static Blob getBlobByHeadUrl(String headUrl) {
    InputStream input = null;
    ByteArrayOutputStream bos = null;
    try {
        URL url = new URL(headUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        // 得到URL的输入流
        input = con.getInputStream();
        byte[] buffer = null;
        bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = input.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        buffer = bos.toByteArray();
        Blob blob=new SerialBlob(buffer);
        return blob;
    } catch (Exception e) {
        log.error("获取微信头像错误!",e);
    } finally {
        try {
            input.close();
            bos.close();
        } catch (IOException e) {
            log.error("关闭流错误!",e);
        }
    }
    return null;
}
发布了5 篇原创文章 · 获赞 0 · 访问量 1504

猜你喜欢

转载自blog.csdn.net/MingFeng197/article/details/89842384
今日推荐