iphone – Objective-C相当于curl请求
发布时间:2020-12-14 20:00:54 所属栏目:百科 来源:网络整理
导读:我试图在Objective-C中操纵这个curl请求: curl -u username:password "http://www.example.com/myapi/getdata" 我实现了以下内容,我得到一个数据获取错误Domain = kCFErrorDomainCFNetwork Code = 303 with NSErrorFailingURLKey = http://www.example.com/
我试图在Objective-C中操纵这个curl请求:
curl -u username:password "http://www.example.com/myapi/getdata" 我实现了以下内容,我得到一个数据获取错误Domain = kCFErrorDomainCFNetwork Code = 303 with NSErrorFailingURLKey = http://www.example.com/myapi/getdata: // Make a call to the API to pull out the categories NSURL *url = [NSURL URLWithString:@"http://www.example.com/myapi/getdata"]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; // Create the username:password string for the request NSString *loginString = [NSString stringWithFormat:@"%@:%@",API_USERNAME,API_PASSWORD]; // Create the authorisation string from the username password string NSData *postData = [loginString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; [request setURL:url]; [request setHTTPMethod:@"GET"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSError *error; NSURLResponse *response; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 我希望有人能够找到我操作卷曲请求并指向正确方向的错误.有什么明显的东西我错过了吗? API返回的数据采用JSON格式. 解决方法
我发现最好的办法是不在代码中尝试身份验证,并将其直接放在URL本身.工作代码如下:
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@www.example.com/myapi/getdata",API_PASSWORD]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setURL:url]; [request setHTTPMethod:@"GET"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; NSError *error; NSURLResponse *response; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |