gpt4 book ai didi

ios - 将 curl 命令转换为 AFNetworking 调用

转载 作者:塔克拉玛干 更新时间:2023-11-01 19:09:56 27 4
gpt4 key购买 nike

我有这个示例电话:

curl -i https://sandbox.espago.com/api/tokens -u publickey: -d "card[first_name]=Jan" -d "card[last_name]=Kowalski" -d "card[number]=4242424242424242" -d "card[verification_value]=123" -d "card[year]=2014" -d "card[month]=02" 

我需要发出 POST (AFNetworking 1.3) 请求,我试过这种方式:

[self.client setAuthorizationHeaderWithUsername:self.publicKey password:@""];
NSDictionary *parameters = (@{
@"card[first_name]" : firstName,
@"card[last_name]" : lastName,
@"card[number]" : cardNumber,
@"card[verification_value]" : verificationCode,
@"card[year]" : @(year),
@"card[month]" : monthString,
});
NSString *path = [NSString stringWithFormat:@"%@/tokens", ZWEspagoURL];
[self.client postPath:path
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {

}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if(completion) completion(nil, error);
}];

但不幸的是,我收到 401 或 422 HTTP 状态代码......

这个 curl 命令是 100% 正常的,没有问题

最佳答案

所以我最终决定使用普通的 NSURLRequest 并放弃 AFNetworking 来实现如此简单的事情,这里是如何将 curl 的 -d 选项转换为 NSURLRequest 模式的代码:

NSDictionary *parameters = (@{
@"card[first_name]" : firstName,
@"card[last_name]" : lastName,
@"card[number]" : [cardNumber stringByReplacingOccurrencesOfString:@" " withString:@""],
@"card[verification_value]" : verificationCode,
@"card[year]" : @(year),
@"card[month]" : monthString,
});
NSMutableArray *httpDataComponents = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in parameters) {
[httpDataComponents addObject:[NSString stringWithFormat:@"%@=%@", key, parameters[key]]];
}
NSString *httpDataString = [httpDataComponents componentsJoinedByString:@"&"];
NSLog(@"http data string %@", httpDataString);
NSString *path = [NSString stringWithFormat:@"%@/tokens", ZWEspagoURL];

NSURL *url = [NSURL URLWithString:path];

NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self publicKey], @""];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedString]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setHTTPBody: [httpDataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
[request setValue:[NSString stringWithFormat:@"%d", httpDataString.length] forHTTPHeaderField:@"Content-Length"];

关于ios - 将 curl 命令转换为 AFNetworking 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19403470/

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