iOS development GET, Post request method (Nsurlconnection)

Source: Internet
Author: User

The primary protocol used by Web service is the HTTP protocol, the Hypertext Transfer Protocol .

The http/1.1 protocol defines a total of 8 request methods (OPTIONS, HEAD, GET, POST, PUT, DELETE, TRACE, CONNECT) as a Web server.

    • The Get method is to send a request to the specified resource, and the requested parameter is "explicitly" behind the URL. A bit like a postcard, the content "explicit" written outside, so the security is relatively poor. Typically used to read data, such as reading a static picture from a server, or querying data.
    • The Post method is to submit data to the specified resource, request the server to process it, and the data is contained in the request body . the parameters and addresses are separated and placed inside the body. a bit like putting the letter in the envelope, the person in contact does not see, the security is relatively high. Typically used for example, submitting a form, uploading a file, and so on (the requested dynamic resource, similar to a query, each method call has to pass many parameters.) )

The IOS SDK provides two different APIs for both synchronous and asynchronous requests for HTTP requests.

    1. Synchronization request, you can request data from the Internet, once the synchronization request is sent, the program will stop user interaction until the server returns data to complete before the next operation, which means that the thread is blocked;
    2. Asynchronous request, does not block the main thread, but will establish a new thread to operate, after the user issued an asynchronous request, still can work on the UI , the program can continue to run;

The main difference between them is that The connection method is different.

The following describes the different situations in the network request by requesting a login interface.

"This development environment: xcode:7.2 IOS Simulator:iphone6 by: Ah left"

First, Get method

1. Synchronize the Get method:

      //1. Create a Web pathNSString *webpath=[nsstring stringWithFormat:@"Http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login", Yourname,yourpass]; Webpath = [Webpath stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];//URL is not allowed for special characters such as Chinese, need to make a string of transcoding as a URL string, such as the space conversion after "%20";Nsurl *url=[Nsurl Urlwithstring:webpath];     //2. Create a request based on the Web pathNsurlrequest *request=[Nsurlrequest Requestwithurl:url];Nsurlresponse *respone;//Gets the response information for the connection, which can be nilNserror *error;//gets the information for the connection error, which can be nil     //3. Get Server DataNSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:respone error:&ERROR];     if(data==Nil)     {NSLog (@"Login failed:%@, please try again", error);         return;     }   /*4. The data obtained by the server is processed accordingly;*/

2. Asynchronous Get Method:

The difference between an asynchronous request and a synchronous request is that the proxy is specified using the Nsurlconnectiondatadelegate delegate protocol.

@interface // Follow the agreement @property (weak,nonatomic) nsmutabledata *receivedata;  // Create a variable data that is used to receive servers asynchronously @end

To create a network request:

   //1. Create a Web pathNSString *webpath=[nsstring stringWithFormat:@"Http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login", Yourname,yourpass]; Webpath=[Webpath stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url=[Nsurl Urlwithstring:webpath]; //2. Create a request based on the Web pathNsurlrequest *request=[Nsurlrequest Requestwithurl:url]; //3. Specify that the agent receives the data asynchronously NsurlconnectiondatadelegateNsurlconnection *con=[nsurlconnection Connectionwithrequest:requestDelegate: Self]; if(con==Nil) {NSLog (@"failed to create connection."); return; }    Else//successfully ready to receive data    {        if(self.receivedata==Nil) {Self.receivedata=[[Nsmutabledata alloc] init]; }    }

Asynchronous proxy behavior:

-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@"has responded successfully.");
//empty to prepare for the current connection self.receiveData.length=0;}-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{NSLog (@"The data has been received."); //append the Received data[Self.receivedata appenddata:data];}-(void) Connectiondidfinishloading: (Nsurlconnection *) connection{NSLog (@"The received data has been completed."); /*The data obtained by the server is receivedata processed accordingly;*/}-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{NSLog (@"The connection failed.");}

Second, POST method

1. Synchronous POST Method:

    //1. Create a Web pathNSString *webpath=@"http://172.16.2.254/php/phoneloginpost.php"; Webpath=[Webpath stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl*url=[Nsurl Urlwithstring:webpath]; //2. Create a request with a protocol cache type (using Nsmutableurlrequest is the key to the Post method)Nsmutableurlrequest *request=[nsmutableurlrequest requestwithurl:url CachePolicy: ( Nsurlrequestuseprotocolcachepolicy) timeOutInterval:Ten]; //3. Set the method for form submission (default is Get)[Request Sethttpmethod:@"Post"]; //4. Set the parameters to be submittedNSString *args=[nsstring stringWithFormat:@"Uname=%@&upas=%@&btn=login", Uname,upas]; [Request Sethttpbody:[args datausingencoding:nsutf8stringencoding];
NSData*recvdata=[nsurlconnection sendsynchronousrequest:request Returningresponse:nil Error:nil]; if(recvdata!=Nil) {
/*
RecvData the data obtained by the server to be processed accordingly
*/
}
Else
{
NSLog (@ " connection failed, please try again! ");
}

The difference between asynchronous and synchronous 2.post methods is that the agent is specified using the Nsurlconnectiondatadelegate delegate protocol.

This is consistent with the Get method, so there is no lengthy demo.

 

The above is a demonstration of partial network synchronous asynchronous request, get, POST request method , because the UI control has other processing not attached, the specific reader can make the appropriate details of the adjustment, to complete the network request project.

As nsurlconnection in IOS9 is declared deprecated in iOS9, it is interesting to refer to the data section of Nsurlsession sending get and POST requests:

synchronous, asynchronous, GET, POST request methods in iOS development (Nsurlsession article)

iOS development GET, Post request method (Nsurlconnection)

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.