需求如下:
同步服務號頭像
初次分析:
實際操作:
实际上,在项目内有已经写好的uploadAvatar方法,以及头像的同步url地址。故只需要从参数拿取avatarUrl参数,并调用上传头像方法。此时需要注意传入参数和已有参数的类型。如需传入头像的FileItem对象,这里就要对url进行处理。具体代码如下:
syncServiceNumber方法中:
String avatarUrl = JsonUtil.getString(data, "avatarUrl");
對拿到的參數進行業務處理:
if (!StringUtil.isEmpty(avatarUrl)) {
//同步头像
try {
FileItem fileItem = urlConvertToFileItem(avatarUrl);
int size = urlGetPictureSize(avatarUrl);
PictureHome.getService().uploadAvatar(sc, fileItem, ServiceNumberHome.UNIT_ID, id, 0, 0, size);
} catch (Exception e) {
System.out.println("----异常:" + avatarUrl);
System.out.println("----异常:" + id);
}
}
转换的工具类:
public static FileItem urlConvertToFileItem(String fileUrl) throws IOException {
URLConnection conn = getUrlConnection(fileUrl);
// 创建输入流读取文件
InputStream in = conn.getInputStream();
FileItem fileItem = createFileItem(in, "itemFileName");//FileItem不用指定路径,内存形势存在。
return fileItem;
}
public static int urlGetPictureSize(String fileUrl) throws IOException {
URLConnection conn = getUrlConnection(fileUrl);
BufferedImage image = ImageIO.read(conn.getInputStream());
int srcWidth = image.getWidth(); // 源图宽度
int srcHeight = image.getHeight(); // 源图高度
int size = srcWidth >= srcHeight ? srcHeight : srcWidth;
return size;
}
private static URLConnection getUrlConnection(String fileUrl) throws IOException {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(30 * 1000); // 连接超时:30s
conn.setReadTimeout(1 * 1000 * 1000); // IO超时:1min
conn.connect();
return conn;
}
至此,任務已經完成。需要詳細瞭解的應該是這個URL轉FileItem的部分。