【问题标题】:What am I doing wrong with NSURLSession that's not allowing me to POST to this API?我做错了什么 NSURLSession 不允许我发布到这个 API?
【发布时间】:2014-01-23 04:22:56
【问题描述】:

我做了一个快速测试项目,并通过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];

我正在尝试 POST 到 this API,这相对简单,我可以使用该链接中的示例 curl 语句,但不能使用 iOS 7 中的新 NSURLSession

我收到此错误:

{"error":"未授权 API 令牌。","errorCode":401}

这绝对是错误的,因为我正在复制并粘贴我登录时使用的 API 密钥。

我做错了什么?

【问题讨论】:

  • 如果您的令牌正确,请联系 www.diffbot.com 支持

标签: ios objective-c ios7 nsurlrequest nsurlsession


【解决方案1】:

遇到了同样的问题。 对我有用的解决方案:

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

代替:

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;

【讨论】:

  • 那么,是什么改变了这项工作?是您将 options:kNilOptions 传递给 NSJSONSerialization 吗?
【解决方案2】:

你所拥有的看起来是正确的。要尝试的一件事是将令牌作为 url 的一部分进行广告: [NSURL URLWithString:@"http://www.diffbot.com/api/batch?token=...."]。如果这不起作用,那么我同意 Johnykutty。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 2017-09-29
    • 1970-01-01
    • 2017-06-13
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多