我正在开发 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 进行连接!我不知道为什么它假设我是。请在发布答案或建议重复之前阅读整个问题。
最佳答案
由于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 的开发者 session “Networking with NSURLSession”
关于ios - AFNetworking 使用 HTTPS 而不是 HTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31634223/