HttpURLConnection下载图片的两种方式

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

转载于:https://www.cnblogs.com/renjiemei1225/p/6114572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值