我试图在 Objective-C 中操纵这个 curl 请求:
curl -u username:password "http://www.example.com/myapi/getdata"
我已经实现了以下内容,并且收到了数据获取Domain=kCFErrorDomainCFNetwork Code=303
错误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];
我希望有人能发现我在尝试操纵 curl 请求时出错的地方,并指出我正确的方向。有什么明显的我错过了吗?从 API 返回的数据是 JSON 格式。