Question

I made a quick test project and through this in the viewDidLoad:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration];
NSURL *url = [NSURL URLWithString:@"http://www.diffbot.com/api/batch"];


NSString *batchJSON = @"[{\"method\":\"GET\",\"relative_url\":\"/api/article?token=...&url=http://www.macrumors.com/2014/01/12/your-verse-ipad-ad/\"}]";
NSDictionary *parameters = @{@"token": @"...",
                             @"batch": batchJSON};

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSError *error;
NSData *parameterData = [NSJSONSerialization dataWithJSONObject:parameters options:kNilOptions error:&error];

request.HTTPBody = parameterData;

NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", dataResponse);
}];

[dataTask resume];

I'm trying to POST to this API which is relatively simple and I can do fine with the example curl statement in that link, but not with the new NSURLSession from iOS 7.

I get this error:

{"error":"Not authorized API token.","errorCode":401}

Which is definitely wrong as I'm copy and pasting the API key I log in with.

What am I doing wrong?

Was it helpful?

Solution

Had the same problem. The solution that worked for me:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";

NSMutableString *requestString = [NSMutableString string];
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
   [requestString appendFormat:@"%@=%@&", key, 
}];

[request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];

Instead of:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSError *error;
NSData *parameterData = [NSJSONSerialization dataWithJSONObject:parameters options:kNilOptions error:&error];

request.HTTPBody = parameterData;

OTHER TIPS

What you have looks correct. One thing to try is to ad the token as part of the url: [NSURL URLWithString:@"http://www.diffbot.com/api/batch?token=...."]. If that does not work, then I agree with Johnykutty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top