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. 解决Cocos2d-x3.1编译生成Android程序出现Android(安卓)NDK:Abor
  2. Android(安卓)APP增量升级的实现方式
  3. Android文件上传
  4. 移植unrar到Android
  5. 2.Retrofit上传list数组给后端
  6. android之获得当前连接wifi的名字
  7. AndroidStudio3.6导入项目出现unable to find valid certificati
  8. Android(安卓)MD5加密
  9. 在android中创建包含对象数组对象List 的Parcelable

随机推荐

  1. 说说android下TV版本UC浏览器模拟鼠标的
  2. android:布局参数,控件属性及各种xml的作
  3. Android学习之Android广播机制
  4. Android8.1以及5.1版本识别sdcard和U盘并
  5. Qt仿Android带特效的数字时钟源码分析(滑
  6. Android(安卓)组件化架构概要
  7. 复制SqlServer数据库的方法
  8. 如何远程连接SQL Server数据库的图文教程
  9. MS SQL SERVER 数据库日志压缩方法与代码
  10. 在程序中压缩sql server2000的数据库备份