Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
【Objective-C】HTTPリクエストサンプル
#import <Foundation/Foundation.h>
#define TIMEOUT_INTERVAL 10
@interface HttpRequestDelegate : NSObject<NSURLConnectionDelegate> {
NSURLConnection *connection;
NSMutableData *receivedData;
NSURLResponse *responseData;
BOOL synchronousOperationComplete;
}
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLResponse *responseData;
@property BOOL synchronousOperationComplete;
@property (retain) id delegate;
- (void)post: (NSString *)urlString postString:(NSString *)postString;
@end
#import "HttpRequestDelegate.h"
@implementation HttpRequestDelegate
@synthesize connection;
@synthesize receivedData;
@synthesize responseData;
@synthesize synchronousOperationComplete;
// ============
// 初期化処理
// ============
- init {
if ((self = [super init])) {}
self.connection = nil;
return self;
}
// ============
// POSTメソッドでHTTPリクエストを送信します
// urString : 送信するURL(http://もしくはhttps://から開始)
// postString : 送信するパラメータ(パラメータ名=値&パラメータ名=値&...)
// (備考)
// - GETメソッドでリクエストを送信する場合は[request setHTTPMethod:@"POST"]を[request setHTTPMethod:@"GET"]に変えるとできます
// - HTTPヘッダ情報は[request setValue:@"値" forHTTPHeaderField:@"HTTPヘッダフィールド名"]で指定できます
// ============
- (void)post:(NSString *)urlString postString:(NSString *)postString {
NSLog(@"POST: %@?%@", urlString, postString);
self.receivedData = [[NSMutableData alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:TIMEOUT_INTERVAL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
if (self.connection == nil) {
self.connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
} else {
self.connection = [self.connection initWithRequest:request delegate:self startImmediately:YES];
}
self.synchronousOperationComplete = NO;
if (!connection) {
NSLog(@"connection failed :(");
} else {
NSLog(@"connection succeeded :)");
}
}
// ============
// Callbacks
// ============
#pragma mark NSURLConnection delegate method
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)redirectResponse {
NSLog(@"Connection received data, retain count");
return request;
}
// ============
// 【デリゲート】サーバからレスポンスが送られてきた時
// ============
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Received response: %@", response);
responseData = [response copy];
[receivedData setLength:0];
}
// ============
// 【デリゲート】サーバからデータが送られてきた時
// ============
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"Received %lu bytes of data", (unsigned long)[data length]);
[receivedData appendData:data];
NSLog(@"Received data is now %lu bytes", (unsigned long)[receivedData length]);
}
// ============
// 【デリゲート】何らかの原因でサーバにつながらなかった時
// ============
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Error receiving response: %@", error);
[[NSAlert alertWithError:error] runModal];
self.synchronousOperationComplete = YES;
}
// ============
// 【デリゲート】データのロードが完了した時
// ============
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %lu bytes of data", (unsigned long)[receivedData length]);
NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"Succeeded! Received data : %@", dataStr);
self.synchronousOperationComplete = YES;
}
@end
// ============
// 実行サンプル
// ============
#import <Cocoa/Cocoa.h>
#import "HttpRequestDelegate.h"
int main(int argc, const char * argv[])
{
// コネクションの確立
HttpRequestDelegate *httpRequest = [[HttpRequestDelegate alloc] init];
// ※パラメータの中に記号(/や&など)がある場合URLパーセントエンコーディングを行う必要があります
// NSString *encodedValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)paramValue, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ));
// HTTPリクエストの送信
NSString *url = @"http://host/"; // TODO ここにURLを記述
NSString *postString = @"paramKey1=paramValue1&paramKey2=paramValue2"; // TODO ここにパラメータを記述
[httpRequest post:url postString:postString];
// HTTPレスポンス待機
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
while (httpRequest.synchronousOperationComplete == NO && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
[NSThread sleepForTimeInterval:1];
}
// HTTPレスポンスデータ受信
NSString *receivedData = [[NSString alloc] initWithData:httpRequest.receivedData encoding:NSUTF8StringEncoding];
NSLog(@"receivedData=%@", receivedData);
return 0;
}
// ============
// 証明書エラー回避(テスト用)
// HTTPリクエスト送信先が https://... の場合で、有効な証明書を持っていない場合、証明書エラーとなる
// 証明書エラーを無視するようにNSURLRequestを拡張する
// ============
#import <Foundation/Foundation.h>
@interface NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
@end
// ============
// 証明書エラー回避(テスト用)
// HTTPリクエスト送信先が https://... の場合で、有効な証明書を持っていない場合、証明書エラーとなる
// 証明書エラーを無視するようにNSURLRequestを拡張する
// ============
#import "NSURLRequest+IgnoreSSL.h"
@implementation NSURLRequest (IgnoreSSL)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host
{
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.