NSURLRequest : Post data and read the posted page
2012-06-11 14:47
489 查看
A few things first
Decide how you want to encode your data - JSON or url-encoding are a good start.
Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
Read up on the URL
Loading System, it's your friend.
Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions
will need to be saved to ivars or in your request's userInfo dict.
Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.
Without further ado, here's a quick and dirty url-encoder:
Using a JSON library like JSONKit makes
encoding things easier, consider it!
转帖:http://stackoverflow.com/questions/10300353/nsurlrequest-post-data-and-read-the-posted-page
Decide how you want to encode your data - JSON or url-encoding are a good start.
Decide upon a return value - will it be 1, TRUE or 0, FALSE, or even YES/non-nil nothing/nil.
Read up on the URL
Loading System, it's your friend.
Aim to make all your url connections asynchronous so your UI remains responsive. You can do this with NSURLConnectionDelegate callbacks. NSURLConnection has a small drawback: your code must be decoupled. Any variables you want available in the delegate functions
will need to be saved to ivars or in your request's userInfo dict.
Alternatively you can use GCD, which, when coupled with the __block qualifiers, allows you to specify error/return code at the point you declare it - useful for one off fetches.
Without further ado, here's a quick and dirty url-encoder:
- (NSData*)encodeDictionary:(NSDictionary*)dictionary { NSMutableArray *parts = [[NSMutableArray alloc] init]; for (NSString *key in dictionary) { NSString *encodedValue = [[dictionary objectForKey:key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *encodedKey = [key stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue]; [parts addObject:part]; } NSString *encodedDictionary = [parts componentsJoinedByString:@"&"]; return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding]; }
Using a JSON library like JSONKit makes
encoding things easier, consider it!
Method 1 - NSURLConnectionDelegate async callbacks:
// .h @interface ViewController : UIViewController<NSURLConnectionDelegate> @end // .m @interface ViewController () { NSMutableData *receivedData_; } @end ... - (IBAction)asyncButtonPushed:(id)sender { NSURL *url = [NSURL URLWithString:@"http://localhost/"]; NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username", @"password", @"password", nil]; NSData *postData = [self encodeDictionary:postDict]; // Create teh requyest NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; [connection start]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData_ setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData_ appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"Succeeded! Received %d bytes of data", [receivedData_ length]); NSString *responeString = [[NSString alloc] initWithData:receivedData_ encoding:NSUTF8StringEncoding]; // Assume lowercase if ([responeString isEqualToString:@"true"]) { // Deal with true return; } // Deal with an error }
Method 2 - Grand Central Dispatch async function:
// .m - (IBAction)dispatchButtonPushed:(id)sender { NSURL *url = [NSURL URLWithString:@"http://www.apple.com/"]; NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username", @"password", @"password", nil]; NSData *postData = [self encodeDictionary:postDict]; // Create teh requyest NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; dispatch_async(dispatch_get_main_queue(), ^{ // Peform the request NSURLResponse *response; NSError *error = nil; NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (error) { // Deal with your error if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response; NSLog(@"HTTP Error: %d %@", httpResponse.statusCode, error); return; } NSLog(@"Error %@", error); return; } NSString *responeString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; // Assume lowercase if ([responeString isEqualToString:@"true"]) { // Deal with true return; } // Deal with an error }); }
Method 3 - Use an NSURLConnection convenience function
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
转帖:http://stackoverflow.com/questions/10300353/nsurlrequest-post-data-and-read-the-posted-page
相关文章推荐
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- Node(6) Accessing GET and POST data using http.ServerRequest
- Post Json Data by Ajax, and Parse the Json Data in backend
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- Craw the data of the web page and parse to pdf
- Submit a POST form and download the result web page
- Using R to read and plot the csv data
- How to use HttpWebRequest to post data to another page which is on another server
- Investigation report of MSSQL data read and write performance
- The Linux Page Cache and pdflush(ZZ)
- could not read data from '/Users/xxxx/xxxx/Info.plist': The file “Info.plist” couldn’t be opened
- [Drupal] Submit and redirect back to the modify page
- What are the most important data structure and algorithms to prepare for Google Interview?
- Get Post Data From Http Request
- R and SAS in the curriculum: getting students to "think with data"
- 迁移zencart后出现 WARNING: An Error occurred, please refresh the page and try again的解决方法
- UIPasteboard Example – Read, Write and Share data between apps
- Use the SQL Server CLR to Read and Write Text Files