gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:38:08 25 4
gpt4 key购买 nike

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

谢谢

关于ios - 如何在 iOS 应用程序中使用带标志的 REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com