- (void)viewDidLoad
{
[super viewDidLoad];
//リクエストを作成
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:@"http://apple.ios.sample.com"]];
[request setTimeoutInterval:30.0];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
//Cookieを保持している場合は読み込む
//TODO Cookieの扱いがおかしい?
NSHTTPCookie *cookie = nil;
NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookie"];
if (cookiesData.length != 0) {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData];
for (cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
} else {
//TODO Cookieが保持されていない
}
NSArray *cookieArray = [NSArray arrayWithObjects: cookie, nil];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];
//ネットワーク接続を開始
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection release];
[request release];
}
#pragma mark -
//サーバーから認証の要求があった時に呼び出される
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
}
//サーバーからレスポンスがあった時に呼び出される
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//Cookieを保存
NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
[[NSUserDefaults standardUserDefaults] setObject:cookiesData
forKey:@"cookie"];
//レスポンスコード取得
statusCode = [((NSHTTPURLResponse *)response) statusCode];
if ([receivedData retainCount]) {
[receivedData release];
}
receivedData = [[NSMutableData alloc] init];
}
//サーバーからデータを受け取ると呼び出される
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
//サーバーからの通信が終わる直前に呼び出される
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//TODO receivedDataにbodyが入っている
}
2013年5月30日木曜日
[iOS]NSURLConnectionを使用してHTTP接続をする。
cookieの保存が必要だったのでメモを残しておく。
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿