Android – 工具类(五):[InternetUtil]网络 (文件下载,图片预览)
public class InternetUtil {
private static final String TAG = "InternetUtil";
public static Bitmap getBitmapFromUrl(String imgUrl){
Bitmap bitmap = null;
try {
URL url = new URL(imgUrl);
InputStream inputStream = url.openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public static void downloadImgFromUrl(String imgUrl, String path, String fileName) {
Bitmap bitmap = getBitmapFromUrl((imgUrl));
BitmapUtil.bitmap2Local(bitmap, path, fileName);
}
public static void downloadFile(String strUrl, String path, String fileName) {
File file = new File(path+File.separator+fileName);
if (file.exists()) {
} else {
try {
URL url = new URL(strUrl);
HttpURLConnection http = (HttpURLConnection) url.openConnection();;
http.connect();
int code = http.getResponseCode();
if(code!=200){
Log.d(TAG, "connect failed!!!");
return;
}
int length = http.getContentLength();
InputStream inputStream = http.getInputStream();
byte[] buffer = new byte[1024];
int len;
OutputStream outputStream = new FileOutputStream(file);
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
Log.d(TAG, "download successful!");
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}