如何在iOS应用程序中使用带有标志的REST API?

时间:2014-09-30 09:20:53

标签: ios web-services curl nsurlconnection

我是iOS开发中的Web服务新手。我有一个带有-a,-b等标志的CURL命令,我必须在iOS应用程序中调用它。没有标志的命令很好但我无法找到带有标志的URL调用的iOS代码段。示例命令是

curl --verbose -a abc.txt -b test.txt http://api.example.com/search.json

谢谢,抱歉英文不好

1 个答案:

答案 0 :(得分:1)

我找到了解决方案并在此处发布了简化的代码部分,首先我从登录响应中创建了cookie:

//Passing parameters in post request

NSDictionary* params = @{
                         @"login":username,
                         @"password":password
                         };
NSMutableString* parameterString = [NSMutableString string];
for(NSString* key in [params allKeys])
{
    if ([parameterString length]) {
        [parameterString appendString:@"&"];
    }
    [parameterString appendFormat:@"%@=%@",key, params[key]];
}
NSString* urlString = [NSString stringWithFormat:URL_USER_LOGIN,APP_KEY];
NSURL* url = [NSURL URLWithString:urlString];

//this is how cookies were created

NSArray* all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:url];
NSHTTPCookie* currentCookie;
for (NSHTTPCookie * cookie in all) {
    NSLog(@"Name: %@ : Value: %@", cookie.name, cookie.value);

    currentCookie= cookie;
}

要使用上面创建的cookie,我将其作为参数传递给函数,名称为“cookie”:

NSString* urlString = [NSString stringWithFormat:@"http://api.example.com/rest.json"];
NSURL* url = [NSURL URLWithString:urlString];
NSURLSession* session =[NSURLSession sharedSession];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[parameterString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPShouldHandleCookies:NO];

NSString* Cookie = [NSString stringWithFormat:@"%@=%@",cookie.name,cookie.value];
[request setValue:Cookie forHTTPHeaderField:@"Cookie"];
__block NSDictionary* jsonResponse;
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if(!error)
    {
          //do something
    }
    else
         //error
 }];
[task resume];

由于