设置NSMutableURLRequest
的“授权”标头时,我的服务器的标头响应不包含该标头:
[Host] => myhost.com
[Content-Type] => application/x-www-form-urlencoded
[Connection] => keep-alive
[Accept] => */*
[User-Agent] => MyApp/1 CFNetwork/758.3.15 Darwin/15.4.0
[Content-Length] => 327
[Accept-Language] => en-gb
[Accept-Encoding] => gzip, deflate
我看到文档建议不在此设置,所以我应该在哪里设置客户端的授权标头?
我的Authorization
标题的目的是发送我的Oauth签名和其他Oauth相关信息
答案 0 :(得分:2)
您拥有用户和密码API
// Create the request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:0];
// New Create the connection
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sharedSession];//sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLCredential *creds = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceForSession];
NSString *authStr = [NSString stringWithFormat:@"%@:%@",self.username,self.password];// @"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
// Part Important
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
// Or Token
NSString *authValueToken = @"OAuth UElJRFER1A5zcGkyW16T0";
[request setValue:authValueToken forHTTPHeaderField:@"AuthenticatedToken"];// Authenticated API
NSString *postLength = [NSString stringWithFormat:@"327"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSString *postLength = [NSString stringWithFormat:@"application/x-www-form-urlencoded"];
[request setValue:postLength forHTTPHeaderField:@"Content-Type"];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
receivedData = [NSMutableData data];
NSString* responseData = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(@"%@",responseData);
if (error) {
[self handleError: error];
}
}];
[dataTask resume]; // <- important
NSLog(@"Header Fields Request--->> %@",request.allHTTPHeaderFields);
答案 1 :(得分:2)
文档建议不要设置它,因为这通常是错误的方法。对于大多数身份验证,您应该在身份验证完成处理程序中创建一个实际的NSURLCredential对象,并且只有在初始尝试访问资源失败后才应该这样做。
不幸的是,AFAIK在操作系统中不支持OAuth,因此您唯一能做的就是指定标题开头,并确保您不会意外添加该主机名的任何其他凭据(因为那样,如果你这样做,你的授权标题就会被踩得很好。