AFNetworking 使用 HTTPS 而不是 HTTP

Posted

技术标签:

【中文标题】AFNetworking 使用 HTTPS 而不是 HTTP【英文标题】:AFNetworking using HTTPS instead of HTTP 【发布时间】:2015-07-26 06:09:10 【问题描述】:

我正在开发 ios 应用程序并尝试使用 AFNetworking。我试图访问一个 http 站点,但我的请求失败,说明它作为 https 请求失败

NSString *urlString = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&APPID=%@",lat, lon, [plistData objectForKey:@"weather"]];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 

以及错误响应

Printing description of error:
Error Domain=NSURLErrorDomain Code=-1004
"Could not connect to the server."
UserInfo=0x7fa104a253d0 
NSUnderlyingError=0x7fa104820950 "Could not connect to the server.", 
NSErrorFailingURLStringKey=https://api.openweathermap.org/data/2.5/weather?lat=[removed]&lon=[removed]&APPID=[removed], 
NSErrorFailingURLKey=https://api.openweathermap.org/data/2.5/weather?lat=[removed]&lon=[removed]&APPID=[removed], _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61,
NSLocalizedDescription=Could not connect to the server.

在测试站点时,它的 https 部分使站点失败。由于我没有将其作为 https 并明确输入 http,所以我不知道出了什么问题。

我正在使用 AFNetworking 2.5.1

需要明确的是,我并没有尝试通过 https 连接!我不知道为什么它假定我是。请在发布答案或建议重复之前阅读整个问题。

【问题讨论】:

我不这么认为,我不想连接https,这个人要连接https。对他们来说,我不确定它是否不允许他们输入 https,或者 https 链接是否不起作用。我尝试连接的 api 不允许 https 连接,这意味着我必须使用 http。 可能 openweathermap 会将您的请求重定向到 https,因此您的网络库无法连接。您不能只说“我不想通过 https 连接”,因为这不取决于您。 如果我尝试在我的浏览器中连接,它可以通过 http 工作而无需重定向。 你能告诉我们你是如何开始operation的吗? completionHandler(weather); failure:^(AFHTTPRequestOperation *operation, NSError *error) Weather *weather; completionHandler(weather); ]; [operation start]; 这是在上面围绕我的成功代码的代码之后 【参考方案1】:

由于 Apple 更改了 App 构建的要求,我需要将 URL 列入白名单

    <key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>api.openweathermap.org</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

以上表示添加到白名单链接所需的 info.plist 这使我可以使用 HTTP 链接。您也可以允许任意加载,但 Apple 不鼓励这样做。如果您想了解更多信息,请查看 Apple 的“使用 NSURLSession 联网”的开发者会话

【讨论】:

【参考方案2】:

使用这个:

operation.securityPolicy.allowInvalidCertificates = YES;

【讨论】:

这没有帮助,它仍在尝试以 https 发送。

以上是关于AFNetworking 使用 HTTPS 而不是 HTTP的主要内容,如果未能解决你的问题,请参考以下文章

使用 SDWebImage 而不是 AFNetworking 进行图像加载有很大的优势吗?

AFNetworking 将 text/html 读取为 html 而不是 JSON

调用 AFNetworking 响应失败块而不是成功块

直接从 AFNetworking 获取 NSData,而不是让它转换为 UIImage

AFNetworking 返回一个 _NSCFData 对象而不是 JSON

AFNetworking 将 NSDictionary 作为单个数组值发送,而不是作为完整对象发送