通过网络地址获取图片(直接上代码)
java后端代码下载工具类
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* 下载工具
*/
public class UploadTools {
/**
* 通过网络地址获取文件InputStream
*
* @param path 地址
* @return
*/
public static InputStream returnBitMap(String path) {
URL url = null;
InputStream is = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream(); //得到网络返回的输入流
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
/**
* 通过网络url取文件,并保存
*
* @param path 文件保存路径
* @param url 网络地址
*/
public void uploadImage(String path, String url) {
try {
URL pathUrl = new URL(url);
DataInputStream dataInputStream = new DataInputStream(pathUrl.openStream());
File file = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while (dataInputStream.read(buffer) > 0) {
fileOutputStream.write(buffer);//将buffer中的字节写入文件中区
}
dataInputStream.close();//关闭输入流
fileOutputStream.close();//关闭输出流
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}