转换目标C的CURL命令 [英] Converting a CURL command for Objective C
本文介绍了转换目标C的CURL命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个困难转换这个curl命令为我的目标C代码:
I'm having a difficulty transforming this curl command for my Objective C Code:
curl -u 0ef106c78146a23becba9105d1e:X -H "Accept: application/json" -H "Content-Type: application/json" https://boomboom.c27.imonggo.com/api/products.json
这是我的目标C代码:
NSError *theError = NULL;
NSURL *theURL = [NSURL URLWithString:@"https://boomboom.c2.imonggo.com/api/products.json"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setValue:@"0ef106c78146a23becba9105d1e" forHTTPHeaderField:@"username"];
[theRequest setValue:@"x" forHTTPHeaderField:@"password"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept:"];
[theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type:"];
NSURLResponse *theResponse = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
很可能我的问题是头字段。
Most likely my problem is with the header fields.
推荐答案
首先,您不需要在HTTP头字段名称中使用冒号。
First of all, you don't need the colon in the HTTP header field name.
重新执行 HTTP身份验证错误。您需要连接用户名和密码, username:password
和Base64编码连接的字符串数据。
使用base64值作为头字段 Authorization
的值,使用下面的代码并放入Base 64编码实现。
Second, you're doing the HTTP authentication wrong. You need to concat your username and password, username:password
and Base64 encode the concatenated string data.
Use the base64 value as value for the header field Authorization
, use the code below and drop in a Base 64 encoding implementation.
// snip
NSMutableUrlRequest* theRequest = [NSMutableUrlRequest ...]
[MyClass httpAuthorizeRequest:theRequest withUsername:@"someuser" andPassword:@"mysecret"];
// snip
+ (void)httpAuthorizeRequest:(NSMutableURLRequest*)request withUsername:(NSString*)username andPassword:(NSString*)password
{
NSString* authorizationToken = [[NSString stringWithFormat:@"%@:%@", username, password] base64Representation];
[request setValue:[NSString stringWithFormat:@"Basic %@", authorizationToken] forHTTPHeaderField:@"Authorization"];
}
这篇关于转换目标C的CURL命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文