2013-07-24 83 views
2

我有一個工作的http GET沒有使用任何第三方位,我是iOS新手,所以這是一個艱難的初始設置。我的代碼如下所示:使用sendSynchronousRequest獲取http響應代碼在ios中使用sendSynchronousRequest

-(NSString *) SendGetRequestToRest:(NSString *)urlEndString 
{ 

NSString *userName = @"userN"; 
NSString *password = @"PassW"; 

NSString *urlBaseString = @"http://someurl.co.uk/"; 

NSString *urlString = [NSString stringWithFormat:@"%@%@", urlBaseString, urlEndString]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

[request setURL:[NSURL URLWithString:urlString]]; 

[request setHTTPMethod:@"GET"]; 

NSString *str1 = [NSString stringWithFormat:@"%@:%@", userName, password]; 
NSString *encodedString = [self stringByBase64EncodingWithString:str1]; 
[request addValue:[NSString stringWithFormat:@"Basic %@",encodedString] forHTTPHeaderField:@"Authorization"]; 

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
NSLog(@"str: %@", str); 

return str; 

} 

我需要做的就是軌道時HTTP GET的狀態代碼是不是一個很好的200,我看到How to check status of web server in iOS?這看起來很有希望,即補充一點:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response 
{ 
    if ([response statusCode] == 404) 
    { 
    /// do some stuff 
    } 
} 

但我不能看到如何將這些連接多達

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

因爲它不接受委託?

回答

11

可以使用returningResponse參數得到 「響應」:

NSHTTPURLResponse *response = nil; 
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; 
if ([response statusCode] == 404) 
{ 
    // Do whatever you want to do after getting response 
} 
相關問題