manager.requestSerializer,
我先设置,再初始化。
悲剧了。
I am getting "Request failed: unauthorized (401)" with the below code:
NSURL *URL = [NSURL URLWithString:@"https://api.parse.com/1/"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager]initWithBaseURL:URL];;
[manager.requestSerializer setValue:@"<Application Id>" forHTTPHeaderField:@"X-Parse-Application-Id"];
[manager.requestSerializer setValue:@"<API Key>" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = @{@"id": @"user123", @"password": @"password123"};
[manager POST:@"users" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
Am I doing something wrong? Any help is appreciated.Thanks.
答案:
(posting again as answer so that working code will appear in code block)
My bad... I am setting the header values before setting up the request serializer. When I set the request serializer, it is discarding previously set headers. In the absence of headers, Parse is throwing 401 error.
Here is the corrected code that is working:
NSURL *URL = [NSURL URLWithString:@"https://api.parse.com/1/"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager]initWithBaseURL:URL];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:@"<Application Id>" forHTTPHeaderField:@"X-Parse-Application-Id"];
[manager.requestSerializer setValue:@"<API Key>" forHTTPHeaderField:@"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSDictionary *parameters = @{@"id": @"user123", @"password": @"password123"};
[manager POST:@"users" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
NSLog(@"Response: %@", responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];