开发者

NSMutableURLRequest with multiple headers

开发者 https://www.devze.com 2023-04-13 04:20 出处:网络
I\'m trying to create a synchronous REST request to an API. The API uses HTTP Basic authentication, so in addition to sending an Accept: application/json header, I need to specify the Authorization he

I'm trying to create a synchronous REST request to an API. The API uses HTTP Basic authentication, so in addition to sending an Accept: application/json header, I need to specify the Authorization header as well with my Base64-encoded username and password pair. When I use just one header the request executes just fine (either successfully authenticating me, or specifying my content format), but when I use both headers, it seems to ignore the Authorization line and returns "HTTP Basic access denied" (presumably a 401).

So I can't for the life of me figure out whats wrong. I'm 100% sure my credentials are valid, because executing the request via REST client works just fine. I'm pretty new to Objective-C so I think perhaps there could be some kind of design pattern I'm not following. Is it valid to call setValue:forKey on an NSMutableDictionary multiple times like that? I also tried using setValue:forHTTPHeader on the request object with the same results.

Here's the code:

NSURL *url = [NSURL URLWithString:@"http://foo.com/api/v1/bar"];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *headers = [NSMutableDictionary dictionary];
NSURLResponse *urlResponse;
NSError *error;

[headers setValue:@"application/json" fo开发者_StackOverflowrKey:@"Accept"];
[headers setValue:@"Basic ..." forKey:@"Authorization"];

[request setAllHTTPHeaderFields:headers];

NSData *urlData = [NSURLConnection sendSynchronousRequest:request 
                                        returningResponse:&urlResponse 
                                                    error:&error];

NSString *responseString = [[NSString alloc] initWithData:urlData 
                                                 encoding:NSUTF8StringEncoding];

NSLog(@"%@",responseString);


The answer is to use:

[request addValue:@"Basic ..." forHTTPHeaderField:@"Authorization"];

Which adds another header into the request instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号