public class Mainactivity extends Activity {
protected static final int SUCCESS = 1;
Private EditText et_id;
Private ImageView img;
Private Handler Handler = new Handler () {
public void Handlemessage (Message msg) {
Switch (msg.what) {
Case SUCCESS:
Bitmap BM = (Bitmap) msg.obj;
Img.setimagebitmap (BM);
Break
Default
Break
}
}
};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
et_id = (EditText) Findviewbyid (r.id.et_id);
img = (ImageView) Findviewbyid (r.id.iv_show);
}
public void Downs (View v) {
//handler+message
Open new threads as long as it is time-consuming
New Thread () {
public void Run () {
Bitmap BM = downimg ();
Message msg = new Message ();
Msg.obj = BM;
Msg.what = SUCCESS;
Handler.sendmessage (msg);
};
}.start ();
}
Public Bitmap downimg () {
String path = Et_id.gettext (). toString (). Trim ();
HttpURLConnection conn = null;
try {
conn = (httpurlconnection) new URL (path). OpenConnection ();
Conn.setconnecttimeout (5000);
Conn.setrequestmethod ("GET");
if (conn.getresponsecode () = = 200) {
InputStream in = Conn.getinputstream ();
Byte[] B = utils.write (in);
Bitmap BM = Bitmapfactory.decodebytearray (b, 0, b.length);
return BM;
} else {
Toast.maketext (Getapplicationcontext (), "Request Failed", "$"). Show ();
}
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
IF (conn! = null) {
Conn.disconnect ();
}
}
return null;
}
}
public class Utils {
public static byte[] Write (InputStream in) {
Bytearrayoutputstream out = new Bytearrayoutputstream ();
byte[] bytes = new byte[1024];
int len = 0;
try {
while (len = in.read (bytes))! =-1) {
Out.write (bytes, 0, Len);
}
return Out.tobytearray ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return null;
}
}
This article is from the "Android Small Notes" blog, please be sure to keep this source http://dreamwing.blog.51cto.com/9872128/1619145
Get data from the server (picture obtained here)