我在iOS应用和带有身份验证令牌系统的网络服务器之间发送数据。令牌是通过带有JWT的登录API生成的,然后本地存储在设备上。当我稍后在加载数据请求中使用它时,我收到状态码为401的-1011错误。 这是我的代码:
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请求在设备上失败。
答案 0 :(得分:0)
您是否尝试使用请求序列化程序的setValue:forHTTPHeaderField:设置授权标头?
/**
Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header.
@param field The HTTP header to set a default value for
@param value The value set as default for the specified header, or `nil`
*/
- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field;
下面写了一个示例,但每个服务器都可以指定如何在授权标头中格式化标记。如果您需要不同的东西,您可以自己设置该标题值。
[requestSerializer setValue:[NSString stringWithFormat:@"token %@", yourToken] forHTTPHeaderField:@"Authorization"];