CURL request in Objective-C (POST)

I am trying to translate these cURL requests to Objective-C (I will be changing the API keys later):

Get a request:

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

      

Post request:

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

      

I got one successful request:

  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];

      

I just can't seem to piece together a complete way to combine these queries sequentially (I've tried http://unirest.io/objective-c.html ). Can anyone point me to a good resource or help me figure out what I am doing wrong?

+3


source to share


1 answer


Check out the code snippet below which will definitely help.



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);

      

+7


source







All Articles