Ios NSURLRequest NSMutableURLRequest Data Request

Source: Internet
Author: User

Ios NSURLRequest NSMutableURLRequest Data Request

Get request

# Pragma mark-GET login-(void) getLogon {// 1. URL NSString * urlStr = [NSString stringWithFormat: @ "http: // localhost/login. php? Username = % @ & password = % @ ", self. userName. text, self. userPwd. text]; NSURL * url = [NSURL URLWithString: urlStr]; // 2. request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. connection // 1> before the logon is complete, no subsequent work can be done! // 2> the logon is in progress. You can do something better! // 3> If the login operation is performed in other threads, the main thread's work will not be blocked. // 4> conclusion: the login operation is asynchronous, and the [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if (connectionError = nil) {// run the command after the network request is completed! // Convert Data to the string NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; // num = 2 NSLog (@ "% @", str, [NSThread currentThread]); // update the interface [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {self. logonResult. text = @ "Logon completed";}] ;}}]; // num = 1 NSLog (@ "come here % @", [NSThread currentThread]); NSURLResponse * response = nil; // 1. does & response really understand it? // 2. error: Why is it NULL, instead of nil // NULL is in C Language = 0 // in C language, it is not dangerous to point the pointer address to 0 // nil is OC, is an empty object to send messages without issues // [response MIMEType]; [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: NULL];}

Post request

# Pragma mark-POST logon-(void) postLogon {// 1. url nsurl * url = [NSURL URLWithString: @ "http: // localhost/login. php "]; // 2. request (a request that can be modified) NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; //? POST // The default value is GET request. HTTPMethod = @ "POST ";//? Data body NSString * str = [NSString stringWithFormat: @ "username =%@ & password =%@", self. userName. text, self. userPwd. text]; // converts a string to a data request. HTTPBody = [str dataUsingEncoding: NSUTF8StringEncoding]; // 3. connection, asynchronous [NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {if (connectionError = = Nil) {// run the command after the network request is completed! // Convert Data to the string NSString * str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; // num = 2 NSLog (@ "% @", str, [NSThread currentThread]); // update the interface [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {self. logonResult. text = str ;}] ;}}]; // num = 1 NSLog (@ "come here % @", [NSThread currentThread]);}

There are two ways to use NSURLConnection: the first is as above, and the second is to implement NSURLConnectionDataDelegate proxy.

-(Void) getLogon {// 1. URL NSString * urlStr = [NSString stringWithFormat: @ "http: // localhost/login. php? Username = % @ & password = % @ ", self. userName. text, self. myPwd]; NSLog (@ "% @", self. myPwd); NSURL * url = [NSURL URLWithString: urlStr]; // 2. request NSURLRequest * request = [NSURLRequest requestWithURL: url]; // 3. connection, over 10 years old // is a very old technology NSURLConnection * connection = [NSURLConnection connectionWithRequest: request delegate: self]; // starts to work in many multithreading technologies, start run dispatch_async (dispatch_queue_create ("demo", DISP ATCH_QUEUE_CONCURRENT), ^ {[connection start];}) ;}# pragma mark-NSURLConnectionDataDelegate proxy method # pragma mark receives the response-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {// preparation work // click the button to have a network request. To avoid repeated open space if (! Self. data) {self. data = [NSMutableData data];} else {[self. data setData: nil] ;}# pragma mark receives data. If the data volume is large, such as a video, it is called multiple times-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {// concatenate the data. The position of the binary stream [self. data appendData: data] ;}# The pragma mark is successfully received and processed.-(void) connectionDidFinishLoading :( NSURLConnection *) connection {// final processing NSString * str = [[NSString alloc] initWithData: self. data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", str, [NSThread currentThread]);} # pragma mark error handling, the possibility of network errors is very high-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "% @", error. localizedDescription );}
Note: UI updates must be performed on the main thread to ensure thread security.

// Update the interface [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {self. logonResult. text = str;}];


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.