Objective-C在iPhone上使用HTTP POST和GET的教程
我下载了苹果的演示,使用HTTP POST和GET(他们的示例应用程序有一个不同部分的tabbar),代码是如此混乱!
有人可以给我一些示例代码或链接到一些教程吗? 🙂
谢谢!
Matt Long的漫游特别好: http : //www.cimgf.com/2010/02/12/accessing-the-cloud-from-cocoa-touch/
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.cimgf.com/testpost.php"]]; [request setHTTPMethod:@"POST"]; [request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"]; NSString *xmlString = @"<data><item>Item 1</item><item>Item 2</item></data>"; [request setValue:[NSString stringWithFormat:@"%d", [xmlString length]] forHTTPHeaderField:@"Content-length"]; [request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]]; [[NSURLConnection alloc] initWithRequest:request delegate:self];
这是一个使用GET的简单方法:
NSURL *url = [NSURL URLWithString:@"http://www.32133.com/test?name=xx"]; NSData *data = [NSData dataWithContentsOfURL:url]; NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"ret=%@", ret);
你也可能想检查一下这个例子
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease]; [request setPostValue:@"Ben" forKey:@"first_name"]; [request setPostValue:@"Copsey" forKey:@"last_name"]; [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
你可以在这里find更多的细节: http : //www.redcodelabs.com/2009/08/objective-c-http-post-get-data/
Objective-C中有很多方法来实现HTTP请求 , CFNetwork
库是为此目的而devise的,但开发http请求最简单的方法是使用NSURLConnection
。
这是一个示例:
NSURLConnection *cmdConn = [[[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES] autorelease];
您将收到didreceiveResponse:
的响应didreceiveResponse:
didreceiveData:
delegates。
希望这会帮助你,如果你想发表一个表格:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"http://www.32133.com/test"]]; [request setHTTPMethod:@"POST"]; NSString *postString = @"name=ivybridge&description=This%20is%20desp."; [request setValue:[NSString stringWithFormat:@"%d", [postString length]] forHTTPHeaderField:@"Content-length"]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; [[NSURLConnection alloc] initWithRequest:request delegate:self];