我试图在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];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。