HttpURLConnection下载图片的两种方式

时间:2023-03-09 03:07:36
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.****.net/ameyume/article/details/6528205