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 the query, each method call to pass a lot of parameters, so you need to use Nsmutableurlrequest to create the request.) )

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

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;

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 the way they connect to each other.

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

First, Get method

1. Synchronize the Get method:

123456789101112131415161718192021222324252627282930313233343536 //1.创建一个web路径NSString *webPath=[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //url不允许为中文等特殊字符,需要进行字符串的转码为URL字符串,例如空格转换后为“%20”;NSURL *url=[NSURL URLWithString:webPath];//2.根据WEB路径创建一个请求NSURLRequest  *request=[NSURLRequest requestWithURL:url];NSURLResponse *respone;//获取连接的响应信息,可以为nilNSError *error;        //获取连接的错误时的信息,可以为nil//3.得到服务器数据NSData  *data=[NSURLConnection sendSynchronousRequest:request returningResponse:respone error:&error];if(data==nil){NSLog(@"登陆失败:%@,请重试",error);return;}/*4.对服务器获取的数据data进行相应的处理;*///1.创建一个web路径NSString *webPath=[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?name=%@&pass=%@&btn=login",yourname,yourpass];webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //url不允许为中文等特殊字符,需要进行字符串的转码为URL字符串,例如空格转换后为“%20”;NSURL *url=[NSURL URLWithString:webPath];//2.根据WEB路径创建一个请求NSURLRequest  *request=[NSURLRequest requestWithURL:url];NSURLResponse *respone;//获取连接的响应信息,可以为nilNSError *error;        //获取连接的错误时的信息,可以为nil//3.得到服务器数据NSData  *data=[NSURLConnection sendSynchronousRequest:request returningResponse:respone error:&error];if(data==nil){NSLog(@"登陆失败:%@,请重试",error);return;}/*4.对服务器获取的数据data进行相应的处理;*/

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.

123456 @interface ViewController : UIViewController // 遵循协议@property (weak,nonatomic) NSMutableData *receiveData;  //创建一个可变data,用于异步接收服务器的数据@end@interface ViewController : UIViewController // 遵循协议@property (weak,nonatomic) NSMutableData *receiveData;  //创建一个可变data,用于异步接收服务器的数据@end

To create a network request:

12345678910111213141516171819202122232425262728293031323334353637383940 //1.创建一个web路径NSString  *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.根据WEB路径创建一个请求NSURLRequest *request=[NSURLRequest requestWithURL:url];//3.指定代理 以异步的方式接收数据NSURLConnectionDataDelegateNSURLConnection  *con=[NSURLConnection connectionWithRequest:request delegate:self];if(con==nil){NSLog(@"创建连接失败.");return;}else//成功 准备接数据{if(self.receiveData==nil){self.receiveData=[[NSMutableData alloc] init];}}//1.创建一个web路径NSString  *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.根据WEB路径创建一个请求NSURLRequest *request=[NSURLRequest requestWithURL:url];//3.指定代理 以异步的方式接收数据NSURLConnectionDataDelegateNSURLConnection  *con=[NSURLConnection connectionWithRequest:request delegate:self];if(con==nil){NSLog(@"创建连接失败.");return;}else//成功 准备接数据{if(self.receiveData==nil){self.receiveData=[[NSMutableData alloc] init];}}

Asynchronous proxy behavior:

1234567891011121314151617181920212223242526272829303132333435363738394041424344 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{NSLog(@"已经响应成功.");   //清空 为当前连接做准备self.receiveData.length=0;}-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{NSLog(@"已经接收到了数据.");//追加接收到的数据[self.receiveData appendData:data];}-(void)connectionDidFinishLoading:(NSURLConnection *)connection{NSLog(@"接收数据已经完成.");/*对服务器获取的数据receiveData进行相应的处理;*/}-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{NSLog(@"连接失败.");}-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{NSLog(@"已经响应成功.");   //清空 为当前连接做准备self.receiveData.length=0;}-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{NSLog(@"已经接收到了数据.");//追加接收到的数据[self.receiveData appendData:data];}-(void)connectionDidFinishLoading:(NSURLConnection *)connection{NSLog(@"接收数据已经完成.");/*对服务器获取的数据receiveData进行相应的处理;*/}-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{NSLog(@"连接失败.");}

Second, POST method

1. Synchronous POST Method:

12345678910111213141516171819202122232425262728 //1.创建一个web路径NSString  *[email protected]"http://172.16.2.254/php/phoneloginpost.php";webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL *url=[NSURL URLWithString:webPath];//2.建立一个带协议缓存类型的请求 (使用NSMutableURLRequest,是post方法的关键)NSMutableURLRequest  *request=[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];//3.设置表单提交的方法(默认为get)[request setHTTPMethod:@"post"];//4.设置要提交的参数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){     /*        对服务器获取的数据recvData进行相应的处理     */}       else{          NSLog(@"连接失败,请重试!");    }//1.创建一个web路径NSString  *[email protected]"http://172.16.2.254/php/phoneloginpost.php";webPath = [webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];NSURL *url=[NSURL URLWithString:webPath];//2.建立一个带协议缓存类型的请求 (使用NSMutableURLRequest,是post方法的关键)NSMutableURLRequest  *request=[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];//3.设置表单提交的方法(默认为get)[request setHTTPMethod:@"post"];//4.设置要提交的参数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){     /*        对服务器获取的数据recvData进行相应的处理     */ }       else{          NSLog(@"连接失败,请重试!");    }

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 about the partial network synchronous asynchronous request, get, the Post request method demonstration, because the UI control also has the other processing not to enclose, the specific reader may carry on the corresponding detail adjustment, carries on the Complete Network request project development.

Since iOS 9 introduced the new network interface Nsurlsession, and Nsurlconnection was declared deprecated in iOS9, it is interesting to refer to the data section of Nsurlsession sending get and POST requests: iOS development GET, Post request method (Nsurlsession article)

iOS development GET, POST request method: Nsurlconnection

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.