【发布时间】:2015-08-17 16:40:07
【问题描述】:
我正在 iOS 应用程序和具有身份验证令牌系统的 Web 服务器之间发送数据。令牌是通过带有 JWT 的登录 API 生成的,然后本地存储在设备上。当我稍后在加载数据请求中使用它时,我收到 -1011 错误,状态码为 401。 这是我的代码:
NSURL *baseURL = [NSURL URLWithString:kBaseURLString];
NSDictionary *parameters = @{@"token": authtoken};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"load_data.php" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
[self doSomeStuff:responseObject];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unable to load data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
如果我使用 curl 和相同的身份验证令牌测试我的 php API,它运行良好。但是使用 iOS 模拟器我得到了这个错误:
ERROR: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: unauthorized (401)" UserInfo=0x79f848f0 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ad59d90> { URL: http://localhost:8888/load_data.php } { status code: 401, headers {
Connection = "Keep-Alive";
"Content-Length" = 12;
"Content-Type" = "text/html;charset=UTF-8";
Date = "Mon, 17 Aug 2015 16:03:44 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.2.29 (Unix) mod_fastcgi/2.4.6 mod_wsgi/3.4 Python/2.7.8 PHP/5.6.2 mod_ssl/2.2.29 OpenSSL/0.9.8za DAV/2 mod_perl/2.0.8 Perl/v5.20.0";
"X-Powered-By" = "PHP/5.6.2";
} }, NSErrorFailingURLKey=http://localhost:8888/load_data.php, NSLocalizedDescription=Request failed: unauthorized (401), com.alamofire.serialization.response.error.data=<556e6175 74686f72 697a6564>}
我在使用 GET 方法时遇到了同样的错误。但是,当我将控制台错误消息中的 url 复制/粘贴到我的浏览器时,它就像一个魅力。我不明白为什么设备上的 AFNetworking 请求失败。
【问题讨论】:
标签: ios token afnetworking-2 http-status-code-401