• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 使用 NSURL 发出 GET 请求不起作用

[复制链接]
菜鸟教程小白 发表于 2022-12-12 09:26:43 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试获取一个简单的 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)connectionNSURLConnection *)connection canAuthenticateAgainstProtectionSpaceNSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connectionNSURLConnection *)connection didReceiveAuthenticationChallengeNSURLAuthenticationChallenge *)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);
        }
    });



Best Answer-推荐答案


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

关于ios - 使用 NSURL 发出 GET 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15280479/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap