IOS develops GET and POST request methods (NSURLConnection) and iosnsurlconnection

Source: Internet
Author: User

IOS develops GET and POST request methods (NSURLConnection) and iosnsurlconnection

The main protocol used by Web Service is HTTP, that isHypertext Transfer Protocol.

HTTP/1.1 defines eight request methods (OPTIONS, HEAD, GET, POST, PUT, DELETE, TRACE, and CONNECT) as Web servers.

  • GET MethodIs to send a request to the specified resource, the request parameter is "explicitly" behind the URL. It is a bit like a postcard. The content is "Explicit", so the security is poor. It is generally used to read data, such as reading static images from the server, or querying data.
  • POST methodIs to submit data to a specified resource and request the server for processing. The data is contained inRequest body. The parameters and addresses are separated and placed in the body. It is a bit like placing the mail content in an envelope, which is invisible to the contacts and is highly secure. It is generally used for submitting forms and uploading files (the requested dynamic resources are similar to queries. Many parameters are required for each method call. Therefore, you need to use NSMutableURLRequest to create a request. )

The iOS SDK provides two different APIs, synchronous and asynchronous, for HTTP requests,

Their main difference lies in their different connection methods.

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

[Development Environment: Xcode: 7.2 iOS Simulator: iphone6 By: ah Left]
 

1. GET Method

1. synchronous get method:

// 1. Create a web path NSString * webPath = [NSString stringWithFormat: @ "http: // 172.16.2.254/php/phonelogin? Name =%@ & pass =%@ & btn = login ", yourname, yourpass]; webPath = [webPath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; // The url cannot contain special characters such as Chinese characters, transcode the string to a URL string. For example, if the space is converted to "% 20", NSURL * url = [NSURL URLWithString: webPath]; // 2. create a request NSURLRequest * request = [NSURLRequest requestWithURL: url]; NSURLResponse * respone; // obtain the connection response information, which can be nil NSError * error; // obtain the connection error information, which can be nil // 3. obtain the server data NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: respone error: & error]; if (data = nil) {NSLog (@ "Logon Failed: % @, please try again ", error); return;}/* 4. process the data obtained by the server ;*/

 

2. asynchronous get method:

The difference between an asynchronous request and a synchronous request is that the NSURLConnectionDataDelegate delegation protocol is used to specify the proxy.

@ Interface ViewController: UIViewController <NSURLConnectionDataDelegate> // follow the protocol @ property (weak, nonatomic) NSMutableData * receiveData; // create a variable data for receiving server data asynchronously @ end

Create a network request:

// 1. Create a web path NSString * webPath = [NSString stringWithFormat: @ "http: // 172.16.2.254/php/phonelogin? Name =%@ & pass =%@ & btn = login ", yourname, yourpass]; webPath = [webPath encoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: webPath]; // 2. create a request NSURLRequest * request = [NSURLRequest requestWithURL: url] According to the WEB path; // 3. specifies that the proxy receives data asynchronously. NSURLConnectionDataDelegate NSURLConnection * con = [NSURLConnection connectionWithRequest: request delegate: self]; if (con = nil) {NSLog (@ "connection creation failed. "); return;} else // The data is successfully prepared. {if (self. receiveData = nil) {self. receiveData = [[NSMutableData alloc] init] ;}}

Asynchronous proxy behavior:

-(Void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {NSLog (@ "response succeeded .");
// Clear the self for the current connection. receiveData. length = 0;}-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {NSLog (@ "received data. "); // append the received data [self. receiveData appendData: data];}-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSLog (@ "receiving data has been completed. ");/* process the receiveData obtained by the server; */}-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "connection failed. ");}

 

Ii. POST Method

1. synchronous post method:

// 1. create a web path NSString * webPath = @ "http: // 172.16.2.254/php/phoneloginpost. php "; webPath = [webPath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: webPath]; // 2. create a request with protocol cache (using NSMutableURLRequest is the key to the post method) NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url cachePolicy :( timeout) timeoutInterval: 10]; // 3. set the form submission method (get by default) [request setHTTPMethod: @ "post"]; // 4. set the NSString * 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 ){
/*
Process the recvData obtained by the server
*/
}
Else
{
NSLog (@ "connection failed. Please try again! ");
}

2. The difference between asynchronous and synchronous post methods is that NSURLConnectionDataDelegate is used to specify the proxy.

This is consistent with the get method, so we will not perform a long demonstration.

The above is a demo of some synchronous and asynchronous network requests and get and post request methods. Since there are other processing methods in the UI control, the specific readers can adjust the corresponding details, complete network request project development.

Since the beginning of iOS, a new network interface NSURLSession was introduced, and in iOS9, NSURLConnection was declared to be deprecated. For more information about NSURLSession sending GET and POST requests, see:

Synchronous, asynchronous, GET, and POST request methods in iOS development (NSURLSession)

 

 

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.