Day04 -- network programming (1), day04 Network Programming

Source: Internet
Author: User

Day04 -- network programming (1), day04 Network Programming

Network Image Viewer
  • Determine the image URL
  • Send http request

    URL url = new URL (address); // gets the connection object and does not establish a connection HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set connection and read timeout conn. setConnectTimeout (5000); conn. setReadTimeout (5000); // set the request method. Note that conn must be capitalized. setRequestMethod ("GET"); // establishes a connection and sends a get request // conn. connect (); // establish a connection and obtain a response. 200 indicates that the request is successfully conn. getResponseCode ();
  • The server image is returned to the browser in the form of a stream

    // Get the InputStream is = conn. getInputStream () returned by the server; // read the data in the stream and construct the image Bitmap bm = BitmapFactory. decodeStream (is );
  • Set the image to the display content of ImageView.

    ImageView iv = (ImageView) findViewById(R.id.iv);iv.setImageBitmap(bm);
  • Add permission
The main thread cannot be blocked.
  • In Android, if the main thread is blocked, the application cannot refresh the ui and respond to user operations, resulting in poor user experience.
  • If the main thread is blocked for too long, the system will throw an ANR exception.
  • ANR: Application Not Response; the Application has no Response
  • No time-consuming operations can be written in the main thread
  • Network interaction is time-consuming. If the network speed is slow, the code will be blocked. Therefore, the code for network interaction cannot run in the main thread.
Only the main thread can refresh the ui
  • The code for refreshing the ui can only run in the main thread, and running in the sub-thread has no effect.
  • To refresh the ui in the Child thread, useMessage Queue Mechanism

    // Message Queue Handler handler = new Handler () {// There Is A looper in the main thread, which constantly checks whether there are new messages in the message queue. If new messages are found, this method is automatically called. Note that this method is the public void handleMessage (android. OS. message msg ){}};

     
    Message Queue 
      
    • Once a logoff finds a Message in the Message Queue, it will take out the Message and throw the Message to the Handler object. Handler will call its own handleMessage method to process the Message.
    • The handleMessage method runs in the main thread.
    • In fact, as long as there is a message in the message queue, it will trigger the main thread to execute the handleMessage method.
    • To put it bluntly, as long as the sub-thread sends messages to the message queue, it will trigger the main thread to execute the handleMessage method.
    • When the main thread is created, the message queue and the poll object will be created, but the message processor object will be created independently when it needs to be used.
  • Send messages to the message queue in a subthread
    // Create the Message object Message msg = new Message (); // The obj attribute of the Message can be assigned to any object, through which the data msg can be carried. obj = bm; // what attribute is equivalent to a tag used to differentiate messages and run the code msg that is not allowed. what = 1; // send the handler message. sendMessage (msg );
  • Use switch statements to differentiate messages

    Public void handleMessage (android. OS. message msg) {switch (msg. what) {// if it is 1, it indicates that the request is successful. case 1: ImageView iv = (ImageView) findViewById (R. id. iv); Bitmap bm = (Bitmap) msg. obj; iv. setImageBitmap (bm); break; case 2: Toast. makeText (MainActivity. this, "request failed", 0 ). show (); break ;}}
Add cache image Function
  • Read the data in the stream returned by the server, and write the data to the local file through the file input stream.

    // 1. the InputStream is = conn. getInputStream (); // 2. read the data in the stream and construct the image FileOutputStream fos = new FileOutputStream (file); byte [] B = new byte [1024]; int len = 0; while (len = is. read (B ))! =-1) {fos. write (B, 0, len );}
  • Code for creating a bitmap object is changed

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
  • Check whether an image with the same name exists in the cache before each request is sent. If so, read the cache.
Obtain open-source websites
  • Code.google.com
  • Github.com
  • Search for smart-image-view on github
  • Download the smart-image-view open-source project
  • When using a custom component, the label name must be the package name.

    <com.loopj.android.image.SmartImageView/>
  • Usage of SmartImageView

    SmartImageView siv = (SmartImageView) findViewById(R.id.siv);siv.setImageUrl("http://192.168.1.102:8080/dd.jpg");
Html source File Viewer
  • Send GET request

    URL url = new URL (path); // get the connection object HttpURLConnection conn = (HttpURLConnection) url. openConnection (); // set the connection property conn. setRequestMethod ("GET"); conn. setConnectTimeout (5000); conn. setReadTimeout (5000); // establish a connection to obtain the response if (conn. getResponseCode () == 200 ){}
  • Obtain the stream returned by the server and read the html source code from the stream.

    Byte [] B = new byte [1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream (); while (len = is. read (B ))! =-1) {// write the read bytes to the byte array and output stream to save bos. write (B, 0, len);} // convert the content in the byte array output stream to a String // utf-8text = new String (bos by default. toByteArray ());
Garbled Processing
  • Garbled characters appear because the server and client code table are inconsistent.

    // Manually specify the code table text = new String (bos. toByteArray (), "gb2312 ");
Submit data in GET Mode
  • The data submitted in get mode is directly spliced 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 with the same code as before

    URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setReadTimeout(5000);conn.setConnectTimeout(5000);if(conn.getResponseCode() == 200){}
  • When the browser sends a request to carry data, it will perform URL encoding for the data. We also need to perform URL encoding for Chinese characters when writing code.

    String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
Submit data in POST Mode
  • Post submits data to the server using a stream.
  • Two attributes are added to the protocol header.

    • Content-Type: application/x-www-form-urlencoded, which describes the mimetype of the submitted data
    • Content-Length: 32, the Length of the submitted data

      // Add the following two attributes 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 () + "");
  • Sets the stream that allows the post request to be opened.

    conn.setDoOutput(true);
  • Gets the output stream of the connection object and writes data to the stream to be submitted to the server.

    OutputStream os = conn.getOutputStream();os.write(data.getBytes());

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.