Android Web Learning to get a picture of the server

Source: Internet
Author: User

First, you need to build a Tomcat server, and then test the image on the server whether the browser on the PC can download it properly.

You can see that the picture data on the server is normally accessible. Image's address: http://localhost:8080/meinv.jpg

How to download pictures from the Internet on our Android?

Get the code for the network picture directly:

public class Mainactivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {s        Uper.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main);        } public void Click (View v) {///1: OK URL String path = "Http://localhost:8080/meinv.jpg";    try {//2: Encapsulate URLs as a URL object url url = new URL (path);    3: Get Connection object for client and server, no connection httpurlconnection conn = (httpurlconnection) url.openconnection () is not established at this time;    4: Initialize the Connection object Conn.setrequestmethod ("GET");    Set connection Timeout conn.setconnecttimeout (5000);    Set read timeout conn.setreadtimeout (5000);    5: A request occurs, establish a connection with the server Conn.connect ();        If the response code is 200, the request succeeds if (conn.getresponsecode () = = 200) {//Gets the stream in the server response header InputStream is = Conn.getinputstream ();        Read the data in the stream and build it into a Bitmap bitmap Bitmap BM = Bitmapfactory.decodestream (IS);    displayed on the interface ImageView ImageView = (ImageView) Findviewbyid (r.id.lv);    Imageview.setimagebitmap (BM); }} catch (Exception e) {//TODO auto-Generated catch Blocke.printstacktrace ();} }}

Run to see the effect:

Printing from the console can be a warning: The network works abnormally in the main thread.

The warning above is introduced from 4.0, and if the network task is in the main thread, a warning is reported. So we need to open a thread to perform the network task.


The modified code is:

public void Click (View v) {//Open a thread threads thread = new Thread () {@Override public void run () {//        TODO auto-generated Method Stub///1: Determine URL String path = "Http://localhost:8080/meinv.jpg";            try {//2: Encapsulate URLs as a URL object url url = new URL (path);        3: Get Connection object for client and server, no connection httpurlconnection conn = (httpurlconnection) url.openconnection () is not established at this time;        4: Initialize the Connection object Conn.setrequestmethod ("GET");        Set connection Timeout conn.setconnecttimeout (5000);        Set read timeout conn.setreadtimeout (5000);        5: A request occurs, establish a connection with the server Conn.connect (); If the response code is 200, the request succeeds if (conn.getresponsecode () = = 200) {//Gets the stream in the server response header InputStream is = Conn.get                InputStream ();                Read the data in the stream and build it into a Bitmap bitmap Bitmap BM = Bitmapfactory.decodestream (IS);        displayed on the interface ImageView ImageView = (ImageView) Findviewbyid (r.id.lv);        Imageview.setimagebitmap (BM); }} catch (ExcePtion e) {//TODO auto-generated catch block E.printstacktrace ();        }    }    };    Start thread Task Thread.Start (); }

Run again to see the effect:

Also reported a warning: Call the error thread exception, that is, only create its view to invoke the view. The straightforward point is that only the main thread (the UI thread) can update the UI, and other threads cannot update the UI casually.

If you need to update the UI, it can only be the main thread to update the UI, how does the other thread tell the main thread to update the UI? This requires the introduction of another knowledge point: the message


If another thread needs to update the UI, a message is sent to the main thread, and the UI is updated automatically when the main course receives it


The code is modified to:

if (conn.getresponsecode () = =)        {        //Gets the stream in the server response header        InputStream is = Conn.getinputstream ();                Read the data in the stream and build it into a Bitmap bitmap        Bitmap BM = Bitmapfactory.decodestream (is);                Message        msg = Handler.obtainmessage () that the update UI has occurred;        Msg.obj = BM;        Handler.sendmessage (msg);        displayed on the interface        //imageview ImageView = (ImageView) Findviewbyid (r.id.lv);        Imageview.setimagebitmap (BM);        }

Join Handler, which is the handle to process messages

Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {//update Uiimageview ImageView = (imageView ) Findviewbyid (r.id.lv); Imageview.setimagebitmap ((Bitmap) msg.obj);};

Run again to see the effect:

You can see that the picture is showing up properly.

We again modify the code to increase the processing logic to get failed

if (conn.getresponsecode () = =)        {        //Gets the stream in the server response header        InputStream is = Conn.getinputstream ();                Read the data in the stream and build it into a Bitmap bitmap        Bitmap BM = Bitmapfactory.decodestream (is);                Message        msg = Handler.obtainmessage () that the update UI has occurred;        Msg.obj = BM;        Msg.what = GET_OK;        Handler.sendmessage (msg);        displayed on the interface        //imageview ImageView = (ImageView) Findviewbyid (r.id.lv);        Imageview.setimagebitmap (BM);        }        else {        //Send get failed message msg = Handler.obtainmessage (); msg.what = Get_error;handler.sendmessage (msg);}

Message processing process:

static final int get_error = 0;static final int Get_ok  = 1; Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {//Update Uiswitch (msg.what) {case get_ok:i Mageview ImageView = (imageView) Findviewbyid (r.id.lv); Imageview.setimagebitmap ((Bitmap) msg.obj); Break;case get_ ERROR:Toast.makeText (Mainactivity.this, "Access failed! ", Toast.length_short). Show (); break;default:break;}};};

We can change the address to show the effect

A brief description of the message mechanism:

1: Occurrence message system uses Message Queuing (MESSAGEQUEUE) and Message polling object (Looper)

2: The function of a message polling object is to constantly detect whether there is caution in the message queue, and if there is a message, the message poll will hand the message object to the Message Processor (Handler), and the processor will call the Handlemessage method to process the message. The Handlemessage method runs in the main thread, so you can refresh the UI


But in the ordinary application, such as a lot of pictures of the circle of Friends, the first time to browse is first slow rushed to the local, the second time to browse directly from the local read, then we can realize:

    public void Click (View v) {//Specifies the path of the file in the Final Document file = new file (Getcachedir (), "info.jpg"); If the file exists, open the IF (file.exists ()) {System.out.println ("read from cache") directly from the local; Bitmap BM = Bitmapfactory.decodefile (File.getabsolutepath ()); ImageView ImageView = (ImageView) Findviewbyid (r.id.lv);    Imageview.setimagebitmap (BM);    }else {System.out.println ("Downloaded from the Internet");        Turn on a thread threads thread = new Thread () {@Override public void run () {//TODO auto-generated method stub        1: OK URL String path = "Http://192.168.1.109:8080/meinv.jpg";            try {//2: Encapsulate URLs as a URL object url url = new URL (path);        3: Get Connection object for client and server, no connection httpurlconnection conn = (httpurlconnection) url.openconnection () is not established at this time;        4: Initialize the Connection object Conn.setrequestmethod ("GET");        Set connection Timeout conn.setconnecttimeout (5000);        Set read timeout conn.setreadtimeout (5000);        5: A request occurs, establish a connection with the server Conn.connect (); If the response code is 200, the request succeeds if (Conn.getresponSecode () = = 200) {//Get the stream in the server response header InputStream is = Conn.getinputstream ();        Read the data from the server return stream, write the data to local, buffer up fileoutputstream fos = new FileOutputStream (file);        Byte[] B = new byte[1024];        int len = 0;        while (len = Is.read (b))! =-1) {fos.write (b, 0, Len);        } fos.close ();                Is.close ();                Load picture from local Bitmap BM = Bitmapfactory.decodefile (File.getabsolutepath ());                Read the data in the stream and build it into a Bitmap bitmap//bitmap BM = Bitmapfactory.decodestream (IS);        Message msg = Handler.obtainmessage () that the update UI has occurred;        Msg.obj = BM;        Msg.what = GET_OK;        Handler.sendmessage (msg);        displayed on the interface//imageview ImageView = (ImageView) Findviewbyid (r.id.lv);        Imageview.setimagebitmap (BM);    } else {//Send get failed message msg = Handler.obtainmessage (); msg.what = Get_error;handler.sendmessage (msg);} } catch (Exception e) {//TODO AuTo-generated Catch block E.printstacktrace ();        }    }    };    Start thread Task Thread.Start (); }    }

Above is the increase from the local buffer to get the picture file.

First run: The Info.jpg file exists under the cache under the package file name

Buffered files

When the exit comes in again, it will be retrieved directly from the buffer.



About getting files from the Web, it's easy to talk about this.








Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Web Learning to get a picture of the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.