2010年 4月 27日(火曜日) 16:27

iPhoneアプリからのHTTP GET/POSTリクエスト

評価:
(0 票)

NSURLConnectionとNSURLRequestを使ってHTTP GET/POSTでWebにアクセスする方法。

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];
}
最終更新日: 2011年 6月 27日(月曜日) 01:24
くらち たかよし

くらち たかよし

モバイル・Webアプリ作家。最近は主にiPhoneアプリ制作を手がける。企画、UIデザイン、設計、実装、テストなどを1人〜数人の個人で行う全人的開発手法の確立を目指している。

使う言語はObjective-C, C++, C#, Java, PHPなど。Web関連で使うものはCakePHP, MySQL, Joomla! CMSなど。デザインではPhotoshopとIllustratorをかろうじて使う。

場所や時間に縛られない、インターネット時代の新しい働き方、自由な生き方を模索中。海外移住、低予算&低リスク起業、キャリアデザイン、心理学などにも興味あり。

Web: awaresoft.jp/