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);
To open a connection using 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);
Convert the resulting data into InputStream
InputStream is = Urlconn.getinputstream ();
Convert InputStream to 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 ();
}
}
Focus: Do not set Setdooutput (true), the POST request upload parameter must be set to true;
It defaults to False:urlConn.setDoOutput (false);
Reference Blog: http://blog.csdn.net/ameyume/article/details/6528205
HttpURLConnection two ways to download pictures