2013-03-07 82 views
2

我想获得一个简单的GET请求来为我的api工作。但它似乎并没有工作,我不知道为什么。使用NSURL不能正常工作的GET请求

我的代码如下

编辑,还试图NSURLCredential但是,这似乎并没有工作,要么

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    NSString *urlAsString = @"https://www.test.com/api/v1/user/logout/"; 
    NSURL *url = [NSURL URLWithString:urlAsString]; 
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f]; 
    [urlRequest setHTTPMethod:@"GET"]; 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) { 
     if ([data length] >0 && error == nil){ 
      NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      NSLog(@"HTML = %@", html); } 
     else if ([data length] == 0 && error == nil){ 
      NSLog(@"Nothing was downloaded."); } 
     else if (error != nil){ 
      NSLog(@"Error happened = %@", error); } 
    }]; 

} 

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { 
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { 
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; 

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; 
} 

我的API吐出JSON。所以,我应该得到一个JSON对象回来,说

success: False 
reason: 'Already Logged out' 

但相反,它给了我下面的错误

2013-03-07 16:24:44.038 test[8957:1d03] Error happened = Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x715db20 {NSErrorFailingURLKey=https://www.test.com/api/v1/user/logout/, NSErrorFailingURLStringKey=https://www.test.com/api/v1/user/logout/, NSUnderlyingError=0x7181cb0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"} 

方法2

一些研制后,我发现发送的另一个碍事请求,并且此方法似乎正常工作

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    dispatch_async(queue, ^{ 
     NSError *error = nil; 
     NSURL *url = [NSURL URLWithString:@"https://www.test.com/api/v1/user/logout/"]; 
     NSString *json = [NSString stringWithContentsOfURL:url 
                encoding:NSASCIIStringEncoding 
                error:&error]; 
     if(!error) { 
      NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding]; 
      NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData 
                    options:kNilOptions 
                     error:&error]; 
      BOOL success = [[jsonDict objectForKey:@"success"] boolValue]; 
      if (!success) { 
       NSString *reason = [jsonDict objectForKey:@"reason"]; 
       NSLog(@"Cannot log out, as user %@", reason); 
      } 
      //NSLog(@"JSON: %@", jsonDict); 
     }else{ 
      NSLog(@"\nJSON: %@ \n Error: %@", json, error); 
     } 
    }); 
+0

'ErrorCode' 1012对应于'NSURLErrorUserCancelledAuthentication',您将必须实现'NSURLConnectionDelegate'的方法'connection:willSendRequestForAuthenticationChallenge:',请参阅[documentation](https://developer.apple.com/library/) mac/documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/Reference/Reference.html#// apple_ref/occ/intfm/NSURLConnectionDelegate/connection:willSendRequestForAuthenticationChallenge :) – tkanzakic 2013-03-07 20:28:05

+0

@tkanzakic谢谢我会研究它。也是我的方法纠正JSON取回? – Jonathan 2013-03-07 20:45:28

+0

是的,它的问题*是你正在使用安全协议,你将不得不管理证书验证,看看[这个其他问题](http://stackoverflow.com/questions/10722272/) ios5-willsendrequestforauthenticationchallenge-method-is-running-recursive),你也可以在SO – tkanzakic 2013-03-07 20:57:45

回答

1

解决问题的方法wa s在API本身。如果用户已经注销,API应该发送HTTPUnauthorized信号。既然如此,iOS就会显示所有这些例外。当我放弃时,只是发回一个简单的JSON响应,一切都得到了修复。