2011/07/12

在iPhone上建立HTTP連線(GET/POST)

HTTP Get
Create request
NSString *str = @"http://my_server/get.php?name=brian&gender=male";
NSString *str_enc = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL URLWithString:str_enc] retain];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];

Prepare delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;


HTTP Post
NSString *content = @"name=brian&gender=male";
NSData *postData = [content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
 
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://my_server/post.php"]];
[request setHTTPMethod:@"POST"];

/* Header */
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

/* Content */
[request setHTTPBody:postData];

connect = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// 跟GET一樣設定4組delegate去接response

參考資料


沒有留言:

張貼留言