授权标头在NSMutableURLRequest中不起作用

时间:2015-05-26 12:10:53

标签: ios objective-c iphone api cocoa-touch

我正在尝试使用NSMutableURLRequest发送cid = @“value”作为授权标头。但它会引发错误。任何帮助,将不胜感激。 这是我的代码

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"url"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"value" forHTTPHeaderField:@"APIAccessKey"];
[request setValue:[NSString stringWithFormat:@"cid=\"%@\"", @"hdemPsqxVSVSJCRSt8PHmUHUyUtXk="]    forHTTPHeaderField:@"Authorization"];

但api返回此错误

 <NSHTTPURLResponse: 0x7fff0a41de80> { URL: http://url } { status code: 401, headers {
    "Cache-Control" = "no-cache";
    "Content-Length" = 31;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Tue, 26 May 2015 11:36:50 GMT";
    Expires = "-1";
    "App-Authenticate" = "Basic Scheme='API' location='https:url";
    Pragma = "no-cache";
    Server = "Microsoft-IIS/7.5";
    "X-AspNet-Version" = "4.0.30319";
    "X-Powered-By" = "ASP.NET";
} }

2 个答案:

答案 0 :(得分:0)

NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                autorelease];

[request setValue:VALUE forHTTPHeaderField:@"field to set"];

或添加标题:

[request addValue:VALUE forHTTPHeaderField:@"field to set"];

答案 1 :(得分:-1)

没有名为'APIAccessKey'的HTTP标头。所以不要写

[request setValue:@"value" forHTTPHeaderField:@"APIAccessKey"];

你应该使用,

[request addValue:@"value" forHTTPHeaderField:@"APIAccessKey"];