我正在使用RESTKit来实现GET请求,并且我希望有一个自定义的http标头。为了让GET请求获得所需的数据,我需要在头文件中发送一个令牌(作为变量)。但是,当我在控制台中查看响应时,它会给我一个401状态代码,这意味着该网站没有获得自定义http标头。我究竟做错了什么导致自定义标头无效。
这是我的代码:
NSIndexSet *statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
NSString *urlString = [NSString stringWithFormat:@"https://foo.com/foo/:foo_number/providers/find?name=%@&location=%@", nameIDTextField.text, locationTextField.text];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//Here is my custom header code
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:url];
[objectManager.HTTPClient setDefaultHeader:@"Auth-Token" value:[[self userAuthTokenMethod] userAuthToken]];
//End of custom header code
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(@"Stuff Here ==> %@", connection);
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[MappingProvider tokenMapping]
pathPattern:@"/v2/styles"
keyPath:@"data"
statusCodes:statusCodeSet];
NSURLRequest *doctorRequest = [NSURLRequest requestWithURL:url];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:doctorRequest
responseDescriptors:@[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
NSLog(@"Mapping Results ==> %@", mappingResult.array);
}
failure:^(RKObjectRequestOperation *operation, NSError *error)
{
NSLog(@"ERROR: %@", error);
NSLog(@"Response: %@", operation.HTTPRequestOperation.responseString);
}];
[operation start];
编辑:
以下是错误日志的一部分:
2013-08-01 22:42:58.547 Empyrean[78461:5803] E restkit.network:RKObjectRequestOperation.m:576 Object request failed: Underlying HTTP request
operation failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200-299), got 401"
如果您发现代码有任何其他问题,请随时指出。
答案 0 :(得分:0)
问题是您正在对象管理器HTTP客户端上设置标头,然后不使用对象管理器,因为您正在显式创建URL请求,然后执行运行它的操作。选择2个选项中的1个并坚持下去。如果您自己创建请求,则还需要向其添加标题。
答案 1 :(得分:0)
您可以使用NSMutableURLRequest
这样最容易解决您的401问题:
NSMutableURLRequest *doctorRequest = [NSMutableURLRequest requestWithURL:url];
[doctorRequest setValue:[[self userAuthTokenMethod] userAuthToken] forHTTPHeaderField:@"Auth-Token"];
除此之外:request
,objectManager
和connection
对象并未真正用于代码的那一部分。当你尝试使用objectManager时,最好为所有请求默认设置头字段。但是,您需要获取objectManager的HTTPClient来为您创建请求。