繁体   English   中英

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

[英]How to use REST API with flags in iOS application?

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

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

谢谢,抱歉英语不好

我找到了解决方案并在此处发布了简化的代码部分,首先,我根据登录响应创建了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];

谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM