Network processing 1-Asynchronous GET request

Source: Internet
Author: User

directory of this document
    • Objective
    • I. Introduction of API
    • Second, send asynchronous GET request
Preface to Cloud Computing

In recent years, cloud computing is a very popular technical term, many experts believe that cloud computing will change the technology base of the Internet, and even affect the entire industry structure. Many people may not understand what cloud computing is, simply put, the user's data (such as documents, photos, etc.), the user needs to use the software, the user needs to search the resources are saved in the "cloud", and do not have to be saved on the user's local. You can think of the "cloud" as a supercomputer, which is actually made up of countless large servers.

Mobile Apps

Now many mobile applications are similar to "cloud computing" models, such as Sina Weibo, the user's data are stored in the Sina server database. When users want to see their Weibo data on their phone, there are a few processes that need to be:

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

2. Return data to client after server response

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

This piece of network processing occupies a very important position in mobile development, and our topic is mainly to learn HTTP requests in iOS network processing.

I. Introduction of API

If you want to send HTTP requests in iOS, there are a number of ways you can choose, and here are a few common ones:

1. Apple's own API

Cfnetwork API in 1> Core Foundation framework: pure C-language API with very high performance

Nsurlconnection api:objective-c API in 2> Foundation framework, performance is also good, easy to use

2.3rd party Open Source framework

1> ASIHTTPRequest

2> afnetworking

Our topic is mainly to study the use of nsurlconnection, as for the 3rd-party framework of learning, there are many resources on the Internet to search.

Back to top two, send an asynchronous GET request

As we all know, there are 2 main requests for http: Get requests and post requests, and then we'll show you how to send a GET request.

It is important to note that you should send an asynchronous request and not send a synchronization request. After the iOS program starts, a main thread, also known as the UI thread, is created by default, which is designed to render UI interfaces, handle UI interfaces, and interact with users, such as handling user touch events, text input events, and so on. The so-called asynchronous request is to send the request in the background thread, not the main thread. Typically, after a client makes a request, it needs to wait for the server's data to be returned, which may take a long time if the server is slow to process or slow. Therefore, if you are determined to send a synchronous request, that is, the main thread to send the request, will cause the main thread block, prone to card machine phenomenon, to the user to bring a very poor experience.

1. Sending asynchronous requests with nsurlconnection
1//Request Address 2 NSString *urlstring = @ "http://192.168.1.102:8080/MJServer/login?username=123&pwd=123"; 3  4//Initialize a Nsurl object 5 nsurl *url = [Nsurl urlwithstring:urlstring]; 6  7//Initialize a request 8 nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; 9//Set request method, can omit, default is GET request.  HttpMethod = @ "GET"; 11//If the server has not been matched after 60 seconds, even if the request times out request.timeoutinterval = 60;13 14//Initialize a connection to nsurlconnection *conn = [Nsurlconnection connectionwithrequest:request delegate:self];16//Start an asynchronous request [Conn start];

1> the 2nd line is the request address, because it is a GET request, the request parameter is directly stitched to the path behind the

2> Line 17th calls Nsurlconnection's Start method to send a HTPP request, which by default is an asynchronous request

2.NSURLConnectionDataDelegate

In the previous 15th line of code, the Nsurlconnection object was initialized with a self acting Proxy (delegate), and my self here is the controller. The client-to-server interaction process constantly sends a message to the proxy object, which is the corresponding method of invoking the proxy object continuously. iOS defines a number of proxy methods in the Nsurlconnectiondatadelegate protocol, and I'm only introducing 3 common methods:

1 #pragma mark-nsurlconnectiondatadelegate 2 #pragma mark is called when the data returned by the server is received (this method may be called multiple times if the data is more than one) 3-(void) connection: (NS URLConnection *) connection didreceivedata: (NSData *) data {4     NSLog (@ "received data returned by the server"); 5     //Splicing data 6     [Self.data Appenddata:data]; 7} 8  9 #pragma mark network connection error when calling connection (void): (nsurlconnection *) connection didfailwitherror: (Nserror *) Error {     NSLog (@ "Network connection error:%@", [Error localizeddescription]),}13 #pragma the mark server's data has been received after the call of-(void) Connectiondidfinishloading: (nsurlconnection *) connection {     NSLog (@ "Server data has been received");/     /parse into string data     NSString *STR = [[[NSString Alloc] initWithData:self.data encoding:nsutf8stringencoding] autorelease];19     NSLog (@ " %@ ", str); 20}

1> the proxy method of line 3rd is called when the server has data returned, and the returned data is passed in nsdata format. This method may be called multiple times if there is more data, such as downloading large files.

2> Line 6th uses a Nsmutabledata object to stitch all the data returned by the server, Self.data is a nsmutabledata.

3> when the server has successfully returned all the data, the proxy method of line 15th is called, and at this end, Self.data contains all the data returned by the server.

4> because my side of the server is returning JSON string data, the 18 row self.data is converted to NSString and printed to see if the data is correct.

3. Encode the Chinese parameters

If your request parameter contains Chinese, you must first encode it and then stitch it back to the request path.

The following request path notation is incorrect:

1 NSString *urlstring = @ "Http://192.168.1.102:8080/MJServer/login?username= hen";

It should be written like this:

1//Use UTF-8 to encode Chinese parameters 2 nsstring *param = [@ "hen" stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];3 4/// Request Address 5 NSString *baseurl = @ "Http://192.168.1.102:8080/MJServer/login?username="; 6 nsstring *urlstring = [BASEURL Stringbyappendingstring:param];

1> Line 2nd uses UTF-8 to encode Chinese parameters

2> the encoded parameter into the request path in line 6th

4. Cancellation Request

If the user's network condition is not very good, then during the login process, the user is likely to click the "Cancel" button to cancel the login

When the user clicks the Cancel button, we should also terminate the previously sent request, this time can do

[Conn Cancel];

Conn is a Nsurlconnection object

The original author, M got a J

Network processing 1-Asynchronous GET request

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.