URL Loading System Programming Guideが参考になりましました。
- (void)sendGetRequest {
NSString *urlstr = @"http://www.yahoo.com/";
NSURL *url = [NSURL URLWithString:urlstr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
if (conn) {
buffer = [[NSMutableData data] retain];
} else {
// error handling
}
}
- (void)sendPostRequest {
NSString *urlstr = @"http://my-test-site/postTest";
NSURL *url = [NSURL URLWithString:urlstr];
NSData *myRequestData = [@"name=Taka&color=black" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
if (conn) {
buffer = [[NSMutableData data] retain];
} else {
// error handling
}
}
- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)res {
NSHTTPURLResponse *hres = (NSHTTPURLResponse *)res;
NSLog(@"Received Response. Status Code: %d", [hres statusCode]);
NSLog(@"Expected ContentLength: %qi", [hres expectedContentLength]);
NSLog(@"MIMEType: %@", [hres MIMEType]);
NSLog(@"Suggested File Name: %@", [hres suggestedFilename]);
NSLog(@"Text Encoding Name: %@", [hres textEncodingName]);
NSLog(@"URL: %@", [hres URL]);
NSLog(@"Received Response. Status Code: %d", [hres statusCode]);
NSDictionary *dict = [hres allHeaderFields];
NSArray *keys = [dict allKeys];
for (int i = 0; i < [keys count]; i++) {
NSLog(@" %@: %@",
[keys objectAtIndex:i],
[dict objectForKey:[keys objectAtIndex:i]]);
}
[buffer setLength:0];
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)receivedData {
[buffer appendData:receivedData];
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error {
[conn release];
[buffer release];
NSLog(@"Connection failed: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
NSLog(@"Succeed!! Received %d bytes of data", [buffer length]);
NSString *contents = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
NSLog(@"%@", contents);
[buffer release];
}





