翻译卷曲请求NSMutableURLRequest [英] Translating cURL request to NSMutableURLRequest

查看:193
本文介绍了翻译卷曲请求NSMutableURLRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新的Objective-C开发,我用卷曲格式的API进行交互。我习惯于让使用URL调用,因此我拼凑从我在互联网络中发现的请求。我仍然无法在拉我的应用程序中的数据。

I'm a new Objective-C developer and I'm interacting with an API in the cURL format. I'm used to making calls using URLs, so I pieced together a request from what I found on the internets. I'm still not able to pull the data in my app.

这是原来的卷曲请求(当然,虚拟键):

This is the original cURL request (with dummy keys of course):

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。任何人对我失去了我的想法?在此先感谢!

I don't get an error, but the jsonResponse returns NULL. Anybody have an idea on what I'm missing? Thanks in advance!

推荐答案

您会看到区别,如果你比较卷曲版本和OBJ-C版本之间的HTTP消息交换。 AFAICS您遗漏了其中指定体的编码内容类型的标题。张贴当你需要传递您是如何编码的身体信息。
这是从我的应用程序之一,一些示例code:

You would see the difference if you compared the HTTP message exchanges between the curl version and your obj-c version. AFAICS you're missing a header for content type where you specify the encoding of the body. When posting you need to pass information on how you are encoding the body. Here is some example code from one of my apps:

- (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;
}

这篇关于翻译卷曲请求NSMutableURLRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆