通过ios中的http请求发送api密钥值(生产密钥)

时间:2014-04-07 17:31:34

标签: ios objective-c

参考这些帖子     Objective-C equivalent of curl requestExecuting curl based actions in Objective-C 我为我的例子尝试了以下代码 我有如下的示例数据

curl --get  'https://www.example.com/xyz' \
     --user 'API_KEY:API_SECRET' \
     --data 'app_id=APP_ID' \
     --data 'metrics=users' \
     --data 'dimensions=day,new_device' \
     --data-urlencode 'conditions={"day":["between","2013-04-01","2013-04-07"]}'

如果我有api密钥(生产密钥),如何检索数据?以及如何使用上述参数检索用户数据?     我尝试这样做,传递参数以通过url检索数据。

-(void)doit
{
    NSString *userName =@"abc@v.com";
    NSString *password =@"cvbnm";

    NSError *myError = nil;


    NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password];
    NSLog(@"loginstring=%@",loginString);


    NSString *accept = [NSString stringWithFormat:@"application/example"];

    NSLog(@"accept %@",accept);
    NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];
    NSLog(@"auth header =%@",authHeader);

    NSURL *url = [NSURL URLWithString:@"https://example.bnm/query"];

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]init];
    request = [NSMutableURLRequest requestWithURL:url];

    [request setURL:url];
    [request setHTTPMethod:@"GET"];
[request setValue:@"users" forKey:@"metrics"];
[request setValue:@"value of api key" forKey:@"API_KEY"];
[request setValue:@"day" forKey:@"dimension"];
[request setValue:@"{"day":["between","2013-04-01","2013-04-07"]}" forKey:@"conditions"];

 NSError *error;
    NSURLResponse *response;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"data : %@",data);

    NSString *result = [NSString stringWithCString:[data bytes] length:[data length]];
     NSLog(@"result = %@",result);
}

但是出了点问题,并没有得到正确的回应。请帮帮我,请告诉我如何解决,任何帮助都会非常棒,如果您需要更多信息,请告诉我

1 个答案:

答案 0 :(得分:0)

问题出在你的台词上     [request setValue:forKey:];

那些实际上没有设置请求体的人,你需要做的是这样的事情:

NSString *stringData = @"app_id=APP_ID&metrics=users&foo=bar";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

然后尝试发布,看看它是否适合你!

修改

我还注意到您未使用身份验证,而您只是记录authHeader