Network processing 1-asynchronous GET request, 1-asynchronous get request

Source: Internet
Author: User

Network processing 1-asynchronous GET request, 1-asynchronous get request
Preface cloud computing

In recent years, cloud computing has become a very popular term. Many experts believe that cloud computing will change the technical foundation of the Internet and even affect the overall industrial landscape. Many people may not know what cloud computing is. Simply put, it refers to the use of user data (such as documents and photos) the software you need to use and the resources you need to search for are stored in the "Cloud" and not stored locally. You can regard "Cloud" as a supercomputer, which is actually composed of countless large servers.

Mobile applications

Nowadays, many mobile applications are similar to the "cloud computing" model, such as Sina Weibo. User data is stored in the database of Sina server. When users want to view their weibo data on their mobile phones, they generally need the following processes:

1. Sina Weibo mobile client sends an HTTP request to the Sina Server

2. The server returns data to the client after responding.

3. The client parses the data and presents it to the user in the form of a graphical interface (such as a list ).

Network processing plays an important role in mobile development. This topic is mainly used to learn about HTTP requests in iOS network processing.

 

Back to Top 1. API Overview

If you want to send Http requests in iOS, there are many options to choose from. Here I will introduce several common ones:

1. API provided by Apple

1> CFNetwork API in Core Foundation framework: API in pure C language with High Performance

2> NSURLConnection API in the Foundation framework: Objective-c api, with good performance and ease of use

2. 3rd-party open-source framework

1> ASIHttpRequest

2> AFNetworking

This topic mainly studies the use of NSURLConnection. As for the learning of the 3rd-party framework, there are many resources available for searching on the Internet.

 

Back to Top 2. Send an asynchronous GET request

As we all know, there are two main HTTP request methods: GET request and POST request. Next we will demonstrate how to send a GET request.

Note that you 'd better send an asynchronous request instead of a synchronous request. After the iOS program is started, the system creates a main thread by default, also known as the UI thread. This main thread is used to render the UI interface and process interaction between the UI interface and users, such as processing users' touch events and text input events. Asynchronous requests are requests sent in the background thread rather than in the main thread. Generally, after a client sends a request, it needs to wait for the server to return data. If the server processing speed is slow or the network speed is slow, it may take a long time. Therefore, if you insist on sending a synchronous request, that is, sending a request in the main thread, it will cause the main thread to be blocked and prone to machine freezing, which will bring users a very poor experience.

1. Use NSURLConnection to send asynchronous requests
1 // request address 2 NSString * urlString = @ "http: // 192.168.1.102: 8080/MJServer/login? Username = 123 & pwd = 123 "; 3 4 // Initialize an NSURL object 5 NSURL * url = [NSURL URLWithString: urlString]; 6 7 // initialize a request 8 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; 9 // set the request method, which can be omitted. The default value is GET request 10. HTTPMethod = @ "GET"; 11 // if the server does not respond after 60 seconds, the request times out by 12 requests. timeoutInterval = 60; 13 14 // initialize a connection 15 NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; 16 // start an asynchronous request 17 [conn start];

1> Row 3 is the request address. Because it is a GET request, the request parameters are directly spliced to

2> line 3 calls the NSURLConnection start method to send an HTPP request, which is an asynchronous request by default.

 

2. NSURLConnectionDataDelegate

In the first line of code, when initializing the NSURLConnection object, a self is passed as a proxy (delegate). Here, self is the controller. In the interaction process between the client and the server, messages are continuously sent to the proxy object, that is, the corresponding methods of the proxy object are continuously called. IOS defines many proxy methods in the NSURLConnectionDataDelegate protocol. Here I will only introduce three common methods:

1 # pragma mark-NSURLConnectionDataDelegate 2 # This method is called when pragma mark receives the data returned by the server (if there is a large amount of data, this method may be called multiple times) 3-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {4 NSLog (@ "data received from the server"); 5 // concatenate data 6 [self. data appendData: data]; 7} 8 9 # Call 10-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) when a pragma mark network connection error occurs *) error {11 NSLog (@ "network connection error: % @", [error localizedDescription]); 12} 13 14 # Call 15-(void) connectionDidFinishLoading :( NSURLConnection *) when the data of The pragma mark server has been received *) connection {16 NSLog (@ "server data has been received"); 17 // parses the data into a string 18 NSString * str = [[NSString alloc] initWithData: self. data encoding: NSUTF8StringEncoding] autorelding]; 19 NSLog (@ "% @", str); 20}

1> when the server returns data, it will call the 3rd-row proxy method. The returned data is passed in as NSData. If there is a large amount of data, such as downloading large files, this method may be called multiple times.

2> Row 3 uses an NSMutableData object to splice all the data returned by the server. self. data is an NSMutableData.

3> when the server has successfully returned all the data, it will call the 15th-row proxy method. So far, the self. data contains all the data returned by the server.

4> because my server returns JSON string data, convert self. data to NSString in line 18 and print it out to see if the data is correct.

 

3. encode Chinese Parameters

If your request parameters contain Chinese characters, you must first encode them and then splice them to the end of the Request Path.

The following Request Path is incorrectly written:

1 NSString * urlString = @ "http: // 192.168.1.102: 8080/MJServer/login? Username = hen ";

It should be written as follows:

1 // encode Chinese Parameters Using UTF-8 2 NSString * param = [@ "hen" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; 3 4 // request address 5 NSString * stringencoding = @ "http: // 192.168.1.102: 8080/MJServer/login? Username = "; 6 NSString * urlString = [baseUrl stringByAppendingString: param];

1> line 1 uses UTF-8 to encode Chinese Parameters

2> splice the encoded parameters in Row 3 to the Request Path.

 

4. Cancel the request

If the user's network conditions are not good, the user may click "cancel" to cancel the logon process.

When the user clicks the cancel button, we should also terminate the previously sent request. This can be done at this time.

[conn cancel];

Conn is an NSURLConnection object.

Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.

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.