相当于 curl 请求的 Objective-C [英] Objective-C equivalent of curl request

查看:33
本文介绍了相当于 curl 请求的 Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 Objective-C 中操作这个 curl 请求:

I'm trying to manipulate this curl request in Objective-C:

curl -u username:password "http://www.example.com/myapi/getdata"

我已经实现了以下内容并且我收到了一个数据获取错误 Domain=kCFErrorDomainCFNetwork Code=303NSErrorFailingURLKey=http://www.example.com/myapi/getdata:

I've implemented the following and I'm getting a data get error 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];

我希望有人能发现我试图操纵 curl 请求时出错的地方,并指出我正确的方向.有什么明显的我错过了吗?API返回的数据为JSON格式.

I was hoping that someone could spot where I am going wrong with my attempt to manipulate the curl request and point me in the correct direction. Is there something obvious I'm missing out? The data returned from the API is in a JSON format.

推荐答案

我发现最好的做法是不要尝试在代码中进行身份验证,而是将其直接放在 URL 本身中.工作代码如下所示:

I found that the best thing to do was to not attempt the authentication within the code and to put it straight in the URL itself. The working code looks as follows:

NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"http://%@:%@@www.example.com/myapi/getdata", API_USERNAME, 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];

这篇关于相当于 curl 请求的 Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆