HttpURLConnection下载图片的两种方式

Posted 跳动的米

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于HttpURLConnection下载图片的两种方式的主要内容,如果未能解决你的问题,请参考以下文章

Android HTTP访问的两种方式(HttpClient和HttpURLConnection)

HttpsURLConnection HttpURLConnection下载图片

通过HttpURLConnection下载图片到本地

HttpURLConnection 下载图片

HttpURLConnection 传输数据和下载图片

Java HttpURLConnection 下载图片 图片全是“加密图片”文字,怎么解决?