java中什么方法可以在微信服务器上面把图片下载到本地服务器并保存(知道微信服务器上面图片的链接)
根据图片链接,转成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();
}
}
}