我是一名新的Objective-C开发人员,我正在使用cURL格式的API进行交互。我习惯使用URL进行调用,所以我将来自互联网上的请求拼凑在一起。我仍然无法在我的应用中提取数据。
这是原始的cURL请求(当然还有虚拟键):
curl -v -H "app_id:12345" -H "app_key:abcdefg" -X POST "http://data.host.com/object" -d '{"Page":0,"Take":10}'
这是我的尝试:
//Request
NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://data.host.com/object"]];
//Set method
request.HTTPMethod = @"POST";
//Set parameters
NSDictionary *parameters = @{
@"Page": @(0),
@"Take": @(10)
};
NSMutableString *parameterString = [NSMutableString string];
for (NSString *key in [parameters allKeys]) {
if ([parameterString length]) {
[parameterString appendString:@"&"];
}
[parameterString appendFormat:@"%@=%@", key, parameters[key]];
}
NSLog(@"PARAMETER STRING: %@",parameterString);
//Set headers
[request setValue:@"12345" forHTTPHeaderField:@"app_id"];
[request setValue:@"abcdefg" forHTTPHeaderField:@"app_key"];
[request setHTTPBody:[parameterString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
if ([data length]) {
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"JSON RESPONSE: %@", jsonResponse);
}
} else {
NSLog(@"%@", error);
}
}];
[task resume];
NSLog(@"TASK: %@", task);
我没有收到错误,但jsonResponse返回NULL。有人知道我错过了什么吗?提前谢谢!
答案 0 :(得分:1)
如果您比较curl版本和obj-c版本之间的HTTP消息交换,您会看到差异。 AFAICS您缺少指定正文编码的内容类型的标题。发布时,您需要传递有关如何编码正文的信息。 以下是我的某个应用中的一些示例代码:
- (NSURLRequest *)createPostRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters {
NSLog(@"startGetTaskForUrl: %@, params %@", url, parameters);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
NSString * httpParams = [self createHttpParameters:parameters];
NSLog(@"HTTPClient: postRequestWithURL body: %@", httpParams);
[request setHTTPBody:[httpParams dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
- (NSString *)urlEncodedUTF8String: (NSString *) source {
return (id)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)source, 0,
(CFStringRef)@";/?:@&=$+{}<>,", kCFStringEncodingUTF8));
}
- (NSString *) createHttpParameters: (NSDictionary *) parameters {
NSMutableString *body = [NSMutableString string];
for (NSString *key in parameters) {
NSString *val = [parameters objectForKey:key];
if ([body length])
[body appendString:@"&"];
[body appendFormat:@"%@=%@", [self urlEncodedUTF8String: [key description]],
[self urlEncodedUTF8String: [val description]]];
}
return body;
}