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

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

问题描述

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

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

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

我实施了以下操作, m获取数据获取错误 Domain = kCFErrorDomainCFNetwork Code = 303 NSErrorFailingURLKey = 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];

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

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