繁体   English   中英

Objective-C中的cURL请求(POST)

[英]cURL request in Objective-C (POST)

我正在努力将这些cURL请求转换为Objective-C(稍后我会更改API密钥):

获取请求:

 curl -v -H "app_id:4bf7860a" -H "app_key:0026e51c7e5074bfe0a0c2d4985804b2" -X GET "http://data.leafly.com/strains/blue-dream"

发布请求:

curl -v -H "app_id:4bf7860a" -H "app_key:0026e51c7e5074bfe0a0c2d4985804b2" -X POST "http://data.leafly.com/strains" -d '{"Page":0,"Take":10}'

到目前为止,我已经能够获得一个成功的请求:

  NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://data.leafly.com/strains/blue-dream"]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField: @"Content-Type"];
    [request addValue:@"4bf7860a" forHTTPHeaderField: @"APP_ID"];
    [request addValue:@"03d3eaa965c5809c5ac06a25505a8fe4" forHTTPHeaderField:@"APP_KEY"];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"Data: %@",data);

        if (error) {
            NSLog(@"ERROR: %@", error);
        } else {
            NSDictionary *jSONresult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            NSLog(@"Strain %@",jSONresult);
        }
    }];
    [task resume];

我只是无法拼凑出一个综合的方法来一致地拼凑这些请求(我已经尝试过http://unirest.io/objective-c.html )。 任何人都可以指出我是一个很好的资源或帮助我思考我做错了什么?

检查下面的代码片段肯定会有所帮助。

NSString *Post = [[NSString alloc] initWithFormat:@"{Page:0, Take:10}"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSURL *url = [NSURL URLWithString:@"http://data.leafly.com/strains"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
[req addValue:@"a2eaffe2" forHTTPHeaderField: @"app_id"];
[req addValue:@"49588984075af3d275a56c93b63eedc0" forHTTPHeaderField:@"app_key"];
[req setHTTPBody:PostData];

NSData *res = [NSURLConnection  sendSynchronousRequest:req returningResponse:NULL error:NULL];
NSString *myString = [[NSString alloc] initWithData:res encoding:NSUTF8StringEncoding];
NSLog(@"%@", myString);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM