gpt4 book ai didi

ios - NSMutableURLRequest 设置授权头

转载 作者:行者123 更新时间:2023-12-01 18:08:20 26 4
gpt4 key购买 nike

当设置 NSMutableURLRequest 的“授权” header 时,我的服务器对 header 的响应不包括该 header :

[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

我阅读了文档建议不要在这里设置它,那么我应该在哪里设置客户端的授权 header ?

我的目的 Authorization header 是发送我的 Oauth 签名和其他 Oauth 相关信息

最佳答案

你有用户和密码 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);

关于ios - NSMutableURLRequest 设置授权头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36872673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com