import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;


public class DownloadFileUtil {


public static Bitmap downloadFile( String url) {
Bitmap bitmap = null;

try {
/*// //////////////取得的是byte数组, 从byte数组生成bitmap
byte[] data = getImage(url);
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);// bitmap
imageView.setImageBitmap(bitmap);// display image
} else {
// Toast.makeText(AndroidTest2_3_3.this, "Image error!",
// 1).show();
}*/


// ******** 取得的是InputStream,直接从InputStream生成bitmap ***********/
bitmap = BitmapFactory.decodeStream(getImageStream(url));



// ********************************************************************/

} catch (Exception e) {
//Toast.makeText(AndroidTest2_3_3.this, "Newwork error!", 1).show();
e.printStackTrace();
}
return bitmap;
}


private static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(inStream);
}
return null;
}


private static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}


private static InputStream getImageStream(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return conn.getInputStream();
}
return null;
}


}

更多相关文章

  1. 2.Retrofit上传list数组给后端
  2. 在android中创建包含对象数组对象List 的Parcelable
  3. android解析二维数组对象key:value
  4. 【Android学习笔记】AutoCompleteTextView(数组在代码中)
  5. Android定义字符串数组资源并在程序中使用
  6. Android资源文件 - 使用资源存储字符串 颜色 尺寸 整型 布尔值
  7. 浅析Android位置权限以及数组寻找索引的坑
  8. android Parcelable序列化数组String[]
  9. Blog-07-《一周快速上手Kotlin For Android》-之数组

随机推荐

  1. Android 序列化之parcelable的简单使用
  2. android 动画实现 xml属性配置说明 AnimU
  3. 22、从头学Android之Android的数据存储--
  4. Android权限操作之uses-permission详解
  5. Android App开发基础篇—四大组件之Activ
  6. android:绘图
  7. Android(安卓)NestedScrolling嵌套滚动的
  8. Android快速入门(一):Android介绍
  9. Android 源码解析-AsyncTask
  10. 初始Android