在NSURLSession中设置CURL参数

时间:2015-12-01 20:45:24

标签: objective-c curl nsurlsession

我正在尝试在Objective-C的Mac应用程序中执行以下CURL命令:

curl -u [USERNAME]:[PASSWORD] -X POST --limit-rate 40000 --header "Content-Type: audio/wav” --header "Transfer-Encoding: chunked" --data-binary @/Users/name/Desktop/test.wav "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true"

我不确定如何在NSURLSession中设置各种CURL参数。我想我正确设置了HTTP标头,但我不知道如何设置ulimit-ratedata-binary参数。这就是我到目前为止所做的:

NSString* credentials = @"[USERNAME]:[PASSWORD]";
NSString* audioPath = @"@/Users/name/Desktop/test.wav";
NSString* fullPath = @"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true";
NSURL* fullURL = [NSURL URLWithString: fullPath];

NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration
                                            defaultSessionConfiguration];
[sessionConfig setHTTPAdditionalHeaders: @{@"Content-Type" : @"audio/wav",
                                           @"Transfer-Encoding": @"chunked"}];

NSMutableData* body = [[NSMutableData alloc] init];
[body appendData: [[NSString stringWithFormat: @"u: %@", credentials]
                   dataUsingEncoding: NSUTF8StringEncoding]];
[body appendData: [@"limit-rate: 40000" dataUsingEncoding: NSUTF8StringEncoding]];
[body appendData: [[NSString stringWithFormat: @"data-binary: %@", audioPath]
                   dataUsingEncoding: NSUTF8StringEncoding]];

NSURLSession* urlSession = [NSURLSession sessionWithConfiguration: sessionConfig];
NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL: fullURL];

[urlRequest setHTTPBody: body];
[urlRequest setHTTPMethod: @"POST"];

NSURLSessionDataTask* dataTask = [urlSession dataTaskWithRequest: urlRequest
                                               completionHandler: ^(NSData* data,
                                                                    NSURLResponse* response,
                                                                    NSError* error) {
    if (nil == error)
    {
        if (0 != [data length])
        {
            // Do something with the returned JSON
        }
        else
            NSLog(@"Data Error: Data is nil or data length is 0.");
    }
    else
        NSLog(@"%@", error);
}];
[dataTask resume];

运行此代码时出现的错误是:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

有人有什么想法吗?我认为它不起作用,因为我错误地设置了CURL参数。

提前致谢!

1 个答案:

答案 0 :(得分:0)

NSURL系列API没有速率限制机制。如果这是一个要求,你将不得不使用libcurl。如果没有,那么:

  • 正文应该是文件的内容(使用NSData的dataWithContentsOfURL:方法)而不是别的。
  • 此处的身份验证过于复杂,无法解释。

一种方法是使用Apple的URL Session Programming Guide描述的技术,该技术描述了如何深入进行HTTP身份验证。

但是,到目前为止,使用NSURL * API进行身份验证的最简单方法是在密钥链中添加Internet密码,如APple Keychain Services Concepts中所述。