1

我正在使用 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"

如果您发现代码有任何其他问题,请随时指出。

4

2 回答 2

0

问题是您在对象管理器 HTTP 客户端上设置标头,然后不使用对象管理器,因为您正在显式创建 URL 请求,然后是运行它的操作。从 2 个选项中选择 1 个并坚持下去。如果您自己创建请求,那么您还需要向其中添加标头。

于 2013-08-02T06:34:49.960 回答
0

您可以使用以下方法最轻松地解决 401 问题NSMutableURLRequest

    NSMutableURLRequest *doctorRequest = [NSMutableURLRequest requestWithURL:url];
    [doctorRequest setValue:[[self userAuthTokenMethod] userAuthToken] forHTTPHeaderField:@"Auth-Token"];

除此之外:request,objectManagerconnection对象并没有真正用于那部分代码。当您尝试使用 objectManager 时,最好为所有请求默认设置标头字段。但是您需要获取 objectManager 的 HTTPClient 来为您创建请求。

于 2013-08-02T07:59:16.397 回答