IOS network programming (HTTP synchronous GET request, synchronous POST request, asynchronous GET request, asynchronous POST request)

Source: Internet
Author: User

 
The following describes some basic concepts: Synchronous requests, asynchronous requests, GET requests, and post requests.

1. synchronous requests request data from the Internet. Once a synchronous request is sent, the program stops user interaction until the server returns data. That is to say, synchronization means that the thread is blocked, and other events are not responded to in the main thread during the synchronization request process until the synchronization request ends.

2. asynchronous requests will not block the main thread, but will create a new thread to operate. After the user sends an asynchronous request, other operations can still be performed, and the program can continue to run. That is to say, Asynchronization does not block the response of the main thread to other events, so the user experience is better than that of synchronous requests.

Asynchronous requests use the nsurlconnection delegation protocol nsurlconnectiondelegate. Different delegate object methods are called back at different stages of the request.

3. The following describes the differences between get and post (from blog http://www.cnblogs.com/wxf0701/archive/2008/08/17/1269798.html)

HTTP defines different methods for interaction with the server. The most basic methods are get and post.

HTTP-GET and HTTP-POST are standard protocol verbs that use HTTP to encode and transmit variable name/variable value pair parameters and use the relevant request semantics. Each HTTP-GET and HTTP-POST is composed of a series of HTTP request headers that define what the client has requested from the server, and the response is composed of a series of HTTP Response Headers and response data, if the request is successful, a response is returned.

The HTTP-GET Passes parameters in the format of urlencoded text that uses the MIME type application/X-WWW-form-urlencoded. Urlencoding is a character encoding that ensures that transmitted parameters are composed of compliant texts. For example, the encoding of a space is "% 20 ". The additional parameter can also be considered as a query string.

Like a HTTP-GET, HTTP-POST parameters are URL encoded. However, the variable name/variable value is not transmitted as part of the URL, but is transmitted within the actual HTTP request message.

(1) get is to get data from the server, and post is to send data to the server.

(1) On the client, the get method submits data through the URL, and the data can be seen in the URL; the POST method places the data in the HTML
Header.

(2) For the get method, the server uses request. querystring to obtain the value of the variable. For the POST method, the server uses request. Form to obtain the submitted data.

(2) data submitted in get mode can contain a maximum of 1024 bytes, whereas post mode does not.

(3) security issues. As mentioned in (1), when get is used, the parameter is displayed in the address bar, but post is not. Therefore, if the data is Chinese and non-sensitive, use get. If the data you enter is not Chinese characters and contains sensitive data, use post as well.

In short, GET requests write parameters directly in the access path. The operation is simple, but it is easy to see from the outside, and the security is not high; the POST request and POST request operations are relatively complicated, and the parameters and addresses need to be separated, but the security is high, and the parameters are placed in the body, not easy to capture.

The following code describes the four request methods.

1. Synchronize GET requests.

// Step 1, create URL nsurl * url = [nsurl urlwithstring: @ "http://api.hudong.com/iphonexml.do? Type = focus-c "]; // Step 2: create a network request via URL nsurlrequest * request = [[nsurlrequest alloc] initwithurl: URL cachepolicy: nsurlrequestuseprotocolcachepolicy timeoutinterval: 10]; // Step 3: connect to the server and send the synchronous request nsdata * received = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: Nil]; nsstring * STR = [[nsstring alloc] initwithdata: received encoding: nsutf8stringencoding]; nslog (@ "data is: % @", STR );

2. synchronous POST requests.

// Step 1, create URL nsurl * url = [nsurl urlwithstring: @ "http://api.hudong.com/iphonexml.do"]; // step 2, create request nsmutableurlrequest * request = [[nsmutableurlrequest alloc] initwithurl: URL cachepolicy: nsurlrequestuseprotocolcachepolicy timeoutinterval: 10]; [Request sethttpmethod: @ "Post"]; // set the request method to post. The default value is get // step 3, connect to the server nsdata * received = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: Nil]; nsstring * str1 = [[nsstring alloc] initwithdata: received encoding: enabled]; nslog (@ "% @", str1 );

Note: nsmutableurlrequest

Nsmutableurlrequest is a subclass of nsurlrequest provided to aid developers who may find it more convenient to mutate a single request object for a series of URL load requests instead of creating an immutable
Nsurlrequest For each load.

3. asynchronous GET requests

// Step 1, create URL nsurl * url = [nsurl urlwithstring: @ "http://api.hudong.com/iphonexml.do? Type = focus-c "]; // Step 2: Create a request for nsurlrequest * request = [[nsurlrequest alloc] initwithurl: URL cachepolicy: nsurlrequestuseprotocolcachepolicy timeoutinterval: 10]; // step 3, connect to the server nsurlconnection * connection = [[nsurlconnection alloc] initwithrequest: Request delegate: Self];

Proxy method:

// Call this method when receiving a response from the server-(void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response {nshttpurlresponse * res = (nshttpurlresponse *) response; nslog (@ "% @", [res allheaderfields]); self. receivedata = [nsmutabledata data];} // this method is called when the server receives the data transmitted. This method is executed several times based on the data size-(void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) Data {[self. receivedata appenddata: Data];} // call this method after data transmission-(void) connectiondidfinishloading :( nsurlconnection *) connection {nsstring * receivestr = [[nsstring alloc] initwithdata: Self. receivedata encoding: nsutf8stringencoding]; nslog (@ "% @", receivestr);} // any errors (Network disconnection, connection timeout, etc.) during network request) will enter this method-(void) connection :( nsurlconnection *) connection didfailwitherror :( nserror *) error {nslog (@ "% @", [error localizeddescription]);}

The following briefly describes the processing content of the first method in the proxy method:

In the didreceiveresponse method, the returns all the HTTP header fields of the specified er. The output is as follows:

 {    "Cache-Control" = "no-cache";    Connection = "Keep-Alive";    "Content-Type" = "text/xml; charset=utf-8";    Date = "Mon, 15 Apr 2013 12:37:54 GMT";    Expires = "Thu, 01 Jan 1970 00:00:00 GMT";    Pragma = "no-cache";    "Proxy-Connection" = "Keep-Alive";    Server = "nginx/0.7.61";    "Set-Cookie" = "JSESSIONID=947667669; domain=.baike.com; path=/, NSC_wt_bqj_ofx-hi=8efb37a6294c;expires=Mon, 15-Apr-13 11:31:28 GMT;path=/";    "Transfer-Encoding" = Identity;    Via = "1.1 WORKISA";}

Iv. asynchronous POST request

// Step 1, create URL nsurl * url = [nsurl urlwithstring: @ "http://api.hudong.com/iphonexml.do"]; // step 2, create request nsmutableurlrequest * request = [[nsmutableurlrequest alloc] initwithurl: URL cachepolicy: nsurlrequestuseprotocolcachepolicy timeoutinterval: 10]; [Request sethttpmethod: @ "Post"]; // set the request method to post. The default value is get // step 3, connect to the server nsurlconnection * connection = [[nsurlconnection alloc] initwithrequest: Request delegate: Self];

The proxy method implements the above asynchronous GET request.

The above code part is reproduced from the http://blog.csdn.net/liulala16/article/details/8271673

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.