Android Network HttpURLConnection captures network images
Package com. liang. netpicture; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. handler; import android. OS. message; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. imageView; import android. widget. toast; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import java.net. URLConnection; public class MainActivity extends ActionBarActivity {ImageView iv_main; private final int SUCCESS = 0; private final int ERROR = 1; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); iv_main = (ImageView) findViewById (R. id. iv_main); // handler accepts the Message final Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {super. handleMessage (msg); if (msg. what = SUCCESS) {iv_main.setImageBitmap (Bitmap) msg. obj);} else {Toast. makeText (MainActivity. this, capture failed, Toast. LENGTH_SHORT ). show () ;}}; // time-consuming operations must be completed in the Child thread, and the component Status of the UI thread cannot be changed in the Child thread, use Handler for Thread communication new Thread (new Runnable () {@ Ov Erride public void run () {Bitmap bitmap = getNetPicture (); Message msg = new Message (); if (bitmap! = Null) {msg. what = SUCCESS; msg. obj = bitmap;} else {msg. what = ERROR;} handler. sendMessage (msg );}}). start ();} private Bitmap getNetPicture () {Bitmap bitmap = null; int responseCode = 0; InputStream is = null; try {URL url = new URL (http://f.hiphotos.baidu.com/image/pic/item/3801213fb80e7beca9bfb6e02d2eb9389b506b4e.jpg ); httpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setReque StMethod (GET); conn. setConnectTimeout (10*1000); conn. setReadTimeout (5*1000); conn. connect (); responseCode = conn. getResponseCode (); if (responseCode = 200) {is = conn. getInputStream (); bitmap = BitmapFactory. decodeStream (is) ;}} catch (IOException e) {Log. I (test, Access failed: + responseCode); e. printStackTrace ();} finally {if (is! = Null) try {is. close () ;}catch (IOException e) {e. printStackTrace () ;}} return bitmap ;}}