我正在使用afnetworking。并在POST请求中获得未经授权的401错误。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
//[manager.requestSerializer setValue:@"" forHTTPHeaderField:@"auth"];
//[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//[manager.requestSerializer setValue:@"Bearer \(token!)" forHTTPHeaderField:@"Authorization"];
//sessionManager.requestSerializer.setValue("Bearer \(token!)", forHTTPHeaderField: "Authorization")
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"%@", responseObject);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"%@", [error description]);
}];
答案 0 :(得分:0)
在.plist中,您是否添加了以下行?
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
答案 1 :(得分:0)
让它使用这些,这段代码可以正常工作:
[request setValue:[dict valueForKey:@"Authorization"]
forHTTPHeaderField:@"Authorization"];
示例代码:
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSLog(@"%@",[dict valueForKey:@"Authorization"]);
[request setValue:[dict valueForKey:@"Authorization"]
forHTTPHeaderField:@"Authorization"];
//NSURLRequest *request =[NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer =[AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
success(responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
id object = [NSJSONSerialization JSONObjectWithData:error.userInfo[AFNetworkingOperationFailingURLResponse DataErrorKey] options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",object);
failure(error);
}];
[operation start];
答案 2 :(得分:0)
我通过转储AFNetworking并使用NSUrlSession代替
解决了这个问题