码迷,mamicode.com
首页 > Web开发 > 详细

HttpURLConnection下载图片的两种方式

时间:2016-11-29 18:59:41      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:stack   yum   url   row   exce   tail   ring   click   lis   

public class MainActivity extends AppCompatActivity {

private ImageView iv;

private String imageurl = "http://img06.tooopen.com/images/20161106/tooopen_sl_185050524199.jpg";
private Bitmap bitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

iv = (ImageView) findViewById(R.id.iv_show);

findViewById(R.id.load).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(loadrunable).start();
}
});
}


private Runnable loadrunable = new Runnable() {

private InputStream is;

@Override
public void run() {

try {
URL imgUrl = new URL(imageurl);
// 使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) imgUrl
.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setRequestMethod("GET");
urlConn.setConnectTimeout(3000);
urlConn.setUseCaches(true);
urlConn.connect();
int code = urlConn.getResponseCode();
Log.e("tag", "run: "+code );
// 将得到的数据转化成InputStream
InputStream is = urlConn.getInputStream();
// 将InputStream转换成Bitmap
// bitmap = getBitmapInputStream(is);

byte[] bytesInputStream = getBytesInputStream(is);
bitmap = BitmapFactory.decodeByteArray(bytesInputStream,0,bytesInputStream.length);

Message msgone = new Message();
msgone.what = 1;
handler.sendMessage(msgone);


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {

if (null != is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// super.handleMessage(msg);
Log.e("tag", "handleMessage: "+msg.what );

if (null != bitmap && null != iv){
iv.setImageBitmap(bitmap);
}
}
};

public Bitmap getBitmapInputStream(InputStream is){
Bitmap bp;
bp = BitmapFactory.decodeStream(is);

return bp;
}

public byte[] getBytesInputStream( InputStream is) throws IOException {

ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[512];
int len;
while ((len = is.read(buff))!= -1){

arrayOutputStream.write(buff,0,len);
}

is.close();
arrayOutputStream.close();

return arrayOutputStream.toByteArray();

}
}

重点:不要设置setDoOutput(true),post请求上传参数得设置为true;
它默认为false: urlConn.setDoOutput(false);

参考博客: http://blog.csdn.net/ameyume/article/details/6528205

HttpURLConnection下载图片的两种方式

标签:stack   yum   url   row   exce   tail   ring   click   lis   

原文地址:http://www.cnblogs.com/renjiemei1225/p/6114572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!