HTTPステータスを取得する
冗長なことが多いObjective-C/Cocoa Foundationでは珍しく少ない行数で書けるHTTP GET/POSTだが、
NSURL* url = [NSURL URLWithString:@"http://hogehost:8080/hogeService"]; NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [req setHTTPMethod:@"POST"]; [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; NSURLResponse* resp = nil; NSError* error = nil; NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error]; NSString* error_str = [error localizedDescription]; if (error_str && error_str.length > 0) { //エラー処理 }
これでは困ることがある。そう、HTTP通信をする時に肝心要のHTTPステータスが判らないのだ。
通常であればレスポンスに返ってきているはずだが、NSURLResponseにHTTPステータスコードを取得するプロパティもメソッドもない。
まさかと思ったのだが..... やっぱりあった。
NSHTTPURLResponse Class Reference
なので、以下のように書けば良いだけだった。
NSHTTPURLResponse* resp = nil; NSError* error = nil; NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error]; if ( resp.statusCode != 200 ) { //エラー処理 } 〜
Javaでもこんな事があったような気がするなぁ。