IOS-network requests

Source: Internet
Author: User

IOS-network requests

Network requests include GET. POST. The steps are as follows: 1> get url. 2> GET request. 3> create a link. 4> return data (proxy ).

1> get the URL.

NSString * urlStr = @ "http://api.zbw.vc/api/vip/GetPhonePadTagMsg"; // when the parameter is Chinese, UTF8 encoding // urlStr = [urlStr encoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: urlStr];

2> GET request.

NSURLRequest *request=[NSURLRequest requestWithURL:url];

By default, parameters of the get method only need URL concatenation.

When creating the post method, perform the following operations on the request:

NSString *dataStr=[NSString stringWithFormat:@"UserName=%@&LoginPwd=%@",self.QQField.text,self.pwdField.text];NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding];[request setHTTPBody:data];[request setHTTPMethod:@"POST"];[request setTimeoutInterval:5.0];

3> create a link.

In this case, the created proxy is the class, so the class must inherit the Protocol

NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];

4> return data (proxy ). To implement proxy, you must implement the following methods:

// Network return data start-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response // call repeatedly, return data processing-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data // return data end-(void) connectionDidFinishLoading :( NSURLConnection *) connection // handle an error-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error


IOS provides another method for data return.

1. Synchronization>

NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: & resp error: & error];

2. asynchronous>

[NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (block)];


The Code is as follows:

# Import "CSZViewController. h "@ interface CSZViewController () @ property (nonatomic, strong) NSMutableData * mutableData; @ end @ implementation CSZViewController-(void) viewDidLoad {[super viewDidLoad];}-(NSURLRequest *) getRequest {NSString * urlStr = @ "http://api.zbw.vc/api/vip/GetPhonePadTagMsg"; // when the parameter is Chinese, UTF8 encoding // urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: urlStr]; NSURLRequest * request = [NSURLRequest requestWithURL: url]; return request;}-(IBAction) getLogin {NSURLRequest * request = [self getRequest]; NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; [conn start];}-(NSMutableURLRequest *) getAsyncRequest {NSString * urlStr = @ "http://api.zbw.vc/api/Vip/PostUserInfo "; NSURL * url = [NSURL URLWithStr Ing: urlStr]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; NSString * dataStr = [NSString stringWithFormat: @ "UserName =%@ & LoginPwd =%@", self. QQField. text, self. pwdField. text]; NSData * data = [dataStr dataUsingEncoding: NSUTF8StringEncoding]; [request setHTTPBody: data]; [request setHTTPMethod: @ "POST"]; [request setTimeoutInterval: 5.0]; return request;}-(IBAction) postLogin {[UIAppl Ication sharedApplication]. networkActivityIndicatorVisible = YES; NSMutableURLRequest * request = [self getAsyncRequest]; NSURLConnection * conn = [NSURLConnection connectionWithRequest: request delegate: self]; [conn start) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {NSLog (@ "% @", @ "Network returned data starts");}-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {if (_ mutableData = nil) {_ mutableData = [NSMutableData data];} [_ mutableData appendData: data];}-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {_ mutableData = nil;}-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSString * str = [[NSString alloc] initWithData: _ mutableData encoding: NSUTF8StringEncoding]; NSLog (@ "% @", str); if (_ mutableDat A! = Nil) {_ mutableData = nil;} [UIApplication sharedApplication]. response = NO;}-(IBAction) clickSync {NSURLRequest * request = [self getRequest]; NSURLResponse * resp = nil; NSError * error = nil; NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: & resp error: & error]; if (error! = Nil) {NSLog (@ "% @", error. localizedDescription); return;} if (data! = Nil) {// decodes NSString * respStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", respStr );} else {NSLog (@ "unable to obtain Network Data") ;}}-(IBAction) clickAsync {NSURLRequest * request = [self getAsyncRequest]; [NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if (ConnectionError! = Nil) {NSLog (@ "% @", connectionError. localizedDescription);} else if (response! = Nil) {// decodes NSString * res = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", res );} else {NSLog (@ "network data not obtained") ;}}] ;}@ end

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.