2014-09-30 43 views
0

我是iOS開發中的Web服務的新手。我有一個帶有像-a,-b等標誌的CURL命令,我必須在iOS應用程序中調用它。沒有標誌的命令是好的,但我無法找到具有標誌的URL調用的iOS片段。示例命令是如何在iOS應用程序中使用帶有標誌的REST API?

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

謝謝,對不起英文不好

+0

顯示您正在使用的代碼。您是否檢查過CURL文檔以找出選項的含義? – Wain 2014-10-01 17:06:58

+1

我想通了,並在答案中發佈瞭解決方案。謝謝Dani – Dani 2014-10-02 13:06:31

回答

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

謝謝

相關問題