【问题标题】:Making a GET request using NSURL not working使用 NSURL 发出 GET 请求不起作用
【发布时间】:2013-03-07 19:53:30
【问题描述】:

我正在尝试获取一个简单的 GET 请求来为我的 api 工作。但它似乎不起作用,我不知道为什么。

我的代码如下

编辑,也尝试过 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.)"}

方法二

经过一番研究,我找到了另一种发送get请求的方法,这种方法似乎工作正常

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);
        }
    });

【问题讨论】:

  • ErrorCode 1012 对应NSURLErrorUserCancelledAuthentication,你必须实现NSURLConnectionDelegate 的方法connection:willSendRequestForAuthenticationChallenge:,见documentation
  • @tkanzakic 谢谢,我会调查的。我的方法对于 json 获取也正确吗?
  • 是的,问题是您使用的是安全协议,您必须管理证书验证,看看this other question,您将还可以在 SO 中找到有关它的更多信息
  • @tkanzakic 最后一个问题,由于这只是一个注销请求,并且不需要在服务器端进行任何身份验证,我还需要使用它吗?因为这需要发送用户名和密码
  • 此认证与https协议有关,与用户认证无关,您必须验证服务器证书

标签: ios


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多