gpt4 book ai didi

ios - 调用内容类型为 : application/x-www-form-urlencoded and Authorization using NSURLSession 的 REST API

转载 作者:行者123 更新时间:2023-11-29 01:17:33 24 4
gpt4 key购买 nike

如何使用 NSURLSession 调用具有 Content-Type: application/x-www-form-urlencoded 和授权的 REST API

Request Url: https://<host>:<port>/signUp
Request Method: POST
Content-Type: application/x-www-form-urlencoded
Accept: application/json
Authorization: MPS ABCDEFGH

输入参数

msg={
"Data": {
"ID": "10",
"req": "HDFC",
"TypeId": "180",
"sd": "MNO"
},
"Cde": "CODE",
"Key": "KEY",
"bcCode": null,
"MCcode": null,
"PinCode": null
}

到目前为止我尝试了什么

-(void)myCallApi
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];


NSString *urlstring=[NSString stringWithFormat:@"https://<host>:<port>/signUp"];
NSURL *url = [NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSString *authValue = [NSString stringWithFormat:@"MPS ABCDEFGH"];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
@"IOS TYPE", @"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:mapData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

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

if([responseString rangeOfString:@"nil"].location != NSNotFound)
{
NSString * newResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

responseString = newResponse;
}

NSLog(@"%@",responseString);
NSLog(@"response %@",response);
NSLog(@"error %@",error);


}];

[postDataTask resume];

}

最佳答案

您需要将 header 键和值添加到 NSURLSessionConfiguration:

configuration.HTTPAdditionalHeaders["Content-Type"] = @"application/x-www-form-urlencoded";

对任何其他 HTTP header (在您的情况下为授权)执行相同的操作。

另请注意,您提交的值(“TEST IOS”和“IOS TYPE”)当前未经过 Url 编码。

使用 stringByAddingPercentEncodingWithAllowedCharacters 对它们进行编码:

[@"TEST IOS" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

关于ios - 调用内容类型为 : application/x-www-form-urlencoded and Authorization using NSURLSession 的 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981247/

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