Android application Development-network programming (i) (re-plate)

Source: Internet
Author: User
Tags response code

Network Picture Viewer

1. Determine the URL of the image

2. Sending an HTTP request

URL url =NewURL (address);// Gets the connection object for the client and server, and no connection has been established at this timeHttpURLConnection conn =(HttpURLConnection) url.openconnection ();// To set the request method, note that you must capitalizeConn.setrequestmethod ("GET");// setting connection and read TimeoutsConn.setconnecttimeout (5000); Conn.setreadtimeout (5000);// send a request to establish a connection with the serverConn.connect ();// If the response code is 200, it indicates that the request was successfulif(Conn.getresponsecode () = = 200){}

3. The image of the server is returned to the browser in the form of a stream.

// get the input stream returned by the server Bitmap BM = Bitmapfactory.decodestream (IS); // read the data in the stream and construct it into a bitmap object

4. Display the bitmap object to ImageView

ImageView IV = (ImageView) Findviewbyid (R.ID.IV); Iv.setimagebitmap (BM);

Need to add permissions

<android:name= "Android.permission.INTERNET"/>

Network requests

Main thread Blocking

In Android, the main thread is blocked causing the UI to stop refreshing, the user experience will be very poor, and if the main thread blocks too long, the ANR (application not responding, application unresponsive) exception will be thrown. Therefore, any time-consuming operation should not be performed on the main thread, otherwise it may block the main thread. Because network interaction is a time-consuming operation, if the speed is slow, the thread is blocked, so the code of the network interaction cannot be written on the main thread

The main thread is also called the UI thread, because the UI can be refreshed only in the main thread. If you need to refresh the UI in a child thread, you need to use the message passing mechanism

Message passing mechanism
  • When the main thread is created, the system creates both the message queue (MessageQueue) object and the message poll (Looper) object

  • The function of a poll is to constantly detect messages in Message Queuing

  • Once Message Queuing has a message, the poll will pass the message object to the Message Processor (Handler)

  • The message Processor calls the Handlemessage () method to process the message, and the Handlemessage () method runs in the main thread, so the UI can be refreshed

    New Android.os.Handler () {      There is a message poll looper in the main thread that constantly detects if there is a new message in the message queue and calls this method automatically if a new message is found. Note This method is run in the main thread, so you can refresh the UIpublic    void  handlemessage (Message msg) {    }};

  • Send a message to the message queue in a child thread

    Message msg = Handler.obtainmessage (); //  creating a Message object, using Handler.obtainmessage () to create a message is more space-saving than direct new msg.obj = BM; // The obj property of the message can be assigned to any object, which enables the message to carry data msg.what = 1;   // What property is equivalent to a label that is used to distinguish different messages from each other, thus running an handler.sendmessage code (MSG); // Send Message

  • Distinguish different messages by switch statements

     Public voidhandlemessage (android.os.Message msg) {Switch(msg.what) {//if it is 1, the message belongs to the successful request     Case1: ImageView IV=(ImageView) Findviewbyid (R.ID.IV); Bitmap BM=(Bitmap) msg.obj;        Iv.setimagebitmap (BM);  Break;  Case2: Toast.maketext (mainactivity. This, "request Failed", 0). Show ();  Break; }       }

Summary: The Handlemessage () method is called whenever there is a message in the message queue. Child threads If you need to refresh the UI, just use the SendMessage () method of the Processor object to send a message to the message queue, triggering the Handlemessage () method to refresh the UI

The ability to add cached images

Reads the data from the stream returned by the server, writes the data to the local file cache.

InputStream is =new  fileoutputstream (file); byte New byte [1024x768]; int len = 0;  while (len = Is.read (b))! =-1) {    0, Len);} Fos.close ();

Reads the cached data and constructs it as a bitmap object

Bitmap BM = Bitmapfactory.decodefile (File.getabsolutepath ());

Detects if there is a picture with the same name in the cache before each request is sent, and if so, reads the cache

Get a Web site with open source code

    • Code.google.com

    • Github.com

Search Smart-image-view on GitHub to download open source projects Smart-image-view

Label name to write package name when using custom components

< Com.loopj.android.image.SmartImageView />

Use of Smartimageview

Smartimageview Siv = (Smartimageview) Findviewbyid (R.ID.SIV); Siv.setimageurl ("http://192.168.1.102:8080/dd.jpg");

HTML Source File Viewer

Send a GET request

New URL (path); // get Connection object, no connection established at this time HttpURLConnection conn = (httpurlconnection) url.openconnection (); // Set connection Properties Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (conn.setreadtimeout); ); // can not write Conn.connect (); // If you do not write Conn.connect (), Getresponsecode () will first establish a connection and then obtain a response code if (Conn.getresponsecode () = =){}

Gets the stream returned by the server and reads the HTML source from the stream

InputStream is =Conn.getinputstream ();byte[] B =New byte[1024];intLen = 0; Bytearrayoutputstream Bos=NewBytearrayoutputstream (); while(len = Is.read (b))! =-1){    //writes the read byte to the byte array output stream and saves it.Bos.write (b, 0, Len);}//converts the contents of a byte array output stream into a string//Android system uses UTF-8 encoding by defaultText =NewString (Bos.tobytearray ());

Handling of garbled characters

Garbled occurs because the server side and the client code table inconsistencies caused by

New String (Bos.tobytearray (), "gb2312"); // manually specify a code table

Submit data

Get method to submit data

The data submitted by the Get method is directly stitched at the end of the URL

Final String Path = "Http://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + Pass;

Send a GET request, the code is the same as before

New= (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (conn.setconnecttimeout); if (Conn.getresponsecode () = =){}

The browser will URL-encode the data when it sends the request, and we need to encode the code in Chinese when we write it (the username name is in Chinese)

Final String Path = "Http://192.168.1.104/Web/servlet/CheckLogin?name=" + urlencoder.encode (name) + "&pass=" + Pass;

Post mode submit data

The post submission data is written to the server using a stream. There are two more properties in the protocol header:

Content-type:application/x-www-form-urlencoded, describing the mimetype of the submitted data

CONTENT-LENGTH:32, describing the length of the submitted data

Add post two properties to the request header String data = "Name=" + urlencoder.encode (name) + "&pass=" + Pass;conn.setrequestproperty ("Content-type", " Application/x-www-form-urlencoded "); Conn.setrequestproperty (" Content-length ", data.length () +" ");

Set the stream that allows the post request to be opened

Conn.setdooutput (true);

Gets the output stream of the connection object, writes the data to be submitted to the server in the stream

OutputStream OS = conn.getoutputstream (); Os.write (Data.getbytes ());

Android application Development-network programming (i) (re-plate)

Related Article

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.