在iOS(当前目标5.0,Base SDK 5.1)中,如何向服务器发送帖子请求,然后阅读页面内容。例如,页面采用用户名和密码,然后回显true或false。这只是为了更好地理解NSURLRequest。
In iOS (current target 5.0, Base SDK 5.1) how can I send a post request to a server, and then read the contents of the page. For example, the page takes a username and password, and then echos true or false. This is just for a better understanding of NSURLRequest.
提前致谢!
推荐答案首先要做的事情
- 决定如何对数据进行编码 - JSON或url编码是一个良好的开端。
- 确定一个返回值 - 它是1,TRUE还是0,FALSE,甚至YES / non-nil nothing / nil。
- 阅读 URL加载系统,这是你的朋友。
- 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.
旨在使所有网址连接异步,以便您的UI保持响应。您可以使用NSURLConnectionDelegate回调执行此操作。 NSURLConnection有一个小缺点:您的代码必须解耦。您希望委托函数中可用的任何变量都需要保存到ivars或请求的userInfo dict中。
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.
或者您可以使用GCD,当与__block限定符结合使用时,允许您在声明它时指定错误/返回代码 - 对于一次提取非常有用。
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]; }使用像 JSONKit 使编码变得更容易,考虑它!
Using a JSON library like JSONKit makes encoding things easier, consider it!
// .h @interface ViewController : UIViewController<NSURLConnectionDelegate> @end // .m @interface ViewController () { NSMutableData *receivedData_; } @end ... - (IBAction)asyncButtonPushed:(id)sender { NSURL *url = [NSURL URLWithString:@"localhost/"]; NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username", @"password", @"password", nil]; NSData *postData = [self encodeDictionary:postDict]; // Create the request 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 }方法2 - Grand Central Dispatch async功能:
Method 2 - Grand Central Dispatch async function:
// .m - (IBAction)dispatchButtonPushed:(id)sender { NSURL *url = [NSURL URLWithString:@"www.apple/"]; NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:@"user", @"username", @"password", @"password", nil]; NSData *postData = [self encodeDictionary:postDict]; // Create the request 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_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 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 // When dealing with UI updates, they must be run on the main queue, ie: // dispatch_async(dispatch_get_main_queue(), ^(void){ // // }); }); }方法3 - 使用NSURLConnection便利功能
Method 3 - Use an NSURLConnection convenience function
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler希望这有帮助。
更多推荐
NSURLRequest:发布数据并阅读发布的页面
发布评论