将 curl 命令转换为 AFNetworking 调用
Posted
技术标签:
【中文标题】将 curl 命令转换为 AFNetworking 调用【英文标题】:Translate curl command to AFNetworking call 【发布时间】:2013-10-16 12:30:08 【问题描述】:我有这个示例调用:
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% 正常,正常工作
【问题讨论】:
您为什么不注销您的请求并根据 curl 请求检查它,看看有什么不同? 你知道我该怎么做吗? NSLog(@"%@", operation.request);在完成块内 这就是我得到的,现在非常有用:所以我最终决定使用普通的 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"];
【讨论】:
以上是关于将 curl 命令转换为 AFNetworking 调用的主要内容,如果未能解决你的问题,请参考以下文章