你的位置:首页 > 操作系统

[操作系统]FatSecret Platform API


  在现阶段饮食类的APP发展的非常迅猛,尤其在校园中,学生只需要凭借一个手机就能买到自己想要的食物,真正做到了足不出户。可是如果我们想独立完成一个app就需要有相应的数据支持,这里给大家介绍一个国外的开发API, FatSecret Platform API,这里面包含了许多的食物信息。我们根据这些信息,就能够请求我们的数据,进行独立的app开发。

1、api地址

  http://platform.fatsecret.com/api/Default.aspx?screen=rapih

2、Authentication 认证

这里要注意,Authentication是难点也是重点,下面我们一起研究研究怎么进行认证。

Note that you must be signed up as a developer, and agree to our Terms of Service in order to obtain you Consumer Key andShared Secret, which you'll need to send requests to the REST API. 

  Api中提到,如果我们需要使用api必须首先注册为开发者,并且获取到Consumer Key andShared Secret这两个东西。好既然这样我们就开始获取,按照网站注册后如会获取如下数据

有了这个东西我们就可以进行下一步了。继续浏览API的Authentication

看到这我们会发现想要请求api必须还得获取一个signature ,而且上面给我们提供了步骤。好那我们就接着往下看

Step 1. Creating a Signature Base String

意思就是说,我们需要将字段和方法按照顺序拼接出下面的形式,其中的转码我们用的是RFC3986

POST & http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api &a%3Dbar%26%26oauth_consumer_key%3Ddemo%26oauth_nonce%3Dabc%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D12345678%26oauth_version%3D1.0%26z%3Dbar

 

  Step 2. Calculating the Signature value (oauth_signature)

意思是说需要进一步RFC2104和RFC2045和RFC3986进行转码

 

Step 3. Sending the Request

Send all the parameters used to generate the Signature Base String via the HTTP method specified in the Signature Base String, with the inclusion of the oauth_signature.

That's it! We will hopefully be able to generate the same oauth_signature from our end and confirm that it is indeed you

  好,看到这里大家肯定有些模糊,没关系,我们有代码帮助大家理解,上面的api步骤,我通过代码翻译如下

/** * <#Description#> * * @param url         请求的地址 * @param method        请求的方法 * @param body         body数据 * @param _oAuthConsumerKey  申请的key * @param _oAuthConsumerSecret 申请的Secret * @param _oAuthToken     暂时用不到 * @param _oAuthTokenSecret  暂时用不到 * * @return <#return value description#> */NSString *OAuthorizationHeader(NSURL *url, NSString *method, NSData *body, NSString *_oAuthConsumerKey, NSString *_oAuthConsumerSecret, NSString *_oAuthToken, NSString *_oAuthTokenSecret){  NSString *_oAuthNonce = [NSString ab_GUID];  NSString *_oAuthTimestamp = [NSString stringWithFormat:@"%d", (int)[[NSDate date] timeIntervalSince1970]];  NSString *_oAuthSignatureMethod = @"HMAC-SHA1";  NSString *_oAuthVersion = @"1.0";    NSMutableDictionary *oAuthAuthorizationParameters = [NSMutableDictionary dictionary];  [oAuthAuthorizationParameters setObject:_oAuthNonce forKey:@"oauth_nonce"];  [oAuthAuthorizationParameters setObject:_oAuthTimestamp forKey:@"oauth_timestamp"];  [oAuthAuthorizationParameters setObject:_oAuthSignatureMethod forKey:@"oauth_signature_method"];  [oAuthAuthorizationParameters setObject:_oAuthVersion forKey:@"oauth_version"];  [oAuthAuthorizationParameters setObject:_oAuthConsumerKey forKey:@"oauth_consumer_key"];  if(_oAuthToken)    [oAuthAuthorizationParameters setObject:_oAuthToken forKey:@"oauth_token"];    // get query and body parameters  NSDictionary *additionalQueryParameters = [NSURL ab_parseURLQueryString:[url query]];  NSDictionary *additionalBodyParameters = nil;  if(body) {    NSString *string = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];    if(string) {      additionalBodyParameters = [NSURL ab_parseURLQueryString:string];    }  }    // combine all parameters  NSMutableDictionary *parameters = [oAuthAuthorizationParameters mutableCopy];  if(additionalQueryParameters) [parameters addEntriesFromDictionary:additionalQueryParameters];  if(additionalBodyParameters) [parameters addEntriesFromDictionary:additionalBodyParameters];    // -> UTF-8 -> RFC3986  NSMutableDictionary *encodedParameters = [NSMutableDictionary dictionary];  for(NSString *key in parameters) {    NSString *value = [parameters objectForKey:key];    [encodedParameters setObject:[value ab_RFC3986EncodedString] forKey:[key ab_RFC3986EncodedString]];  }    NSArray *sortedKeys = [[encodedParameters allKeys] sortedArrayUsingFunction:SortParameter context:(__bridge void *)(encodedParameters)];    NSMutableArray *parameterArray = [NSMutableArray array];  for(NSString *key in sortedKeys) {    [parameterArray addObject:[NSString stringWithFormat:@"%@=%@", key, [encodedParameters objectForKey:key]]];  }  NSString *normalizedParameterString = [parameterArray componentsJoinedByString:@"&"];    NSString *normalizedURLString;  if ([url port] == nil) {    normalizedURLString = [NSString stringWithFormat:@"%@://%@%@", [url scheme], [url host], [url path]];  } else {    normalizedURLString = [NSString stringWithFormat:@"%@://%@:%@%@", [url scheme], [url host], [url port], [url path]];  }    NSString *signatureBaseString = [NSString stringWithFormat:@"%@&%@&%@",                   [method ab_RFC3986EncodedString],                   [normalizedURLString ab_RFC3986EncodedString],                   [normalizedParameterString ab_RFC3986EncodedString]];    NSString *key = [NSString stringWithFormat:@"%@&%@",           [_oAuthConsumerSecret ab_RFC3986EncodedString],           [_oAuthTokenSecret ab_RFC3986EncodedString]];    NSData *signature = HMAC_SHA1(signatureBaseString, key);  NSString *base64Signature = [signature base64EncodedString];    // PARKER CHANGE: changed oAuthAuthorizationParameters to parameters  NSMutableDictionary *authorizationHeaderDictionary = [parameters mutableCopy];  [authorizationHeaderDictionary setObject:base64Signature forKey:@"oauth_signature"];    NSMutableArray *authorizationHeaderItems = [NSMutableArray array];  for(NSString *key in authorizationHeaderDictionary) {    NSString *value = [authorizationHeaderDictionary objectForKey:key];    // PARKER CHANGE: removed quotes that surrounded each value    [authorizationHeaderItems addObject:[NSString stringWithFormat:@"%@=%@",                       [key ab_RFC3986EncodedString],                       [value ab_RFC3986EncodedString]]];  }    // PARKER CHANGE: changed concatentation string from ", " to "&"  NSString *authorizationHeaderString = [authorizationHeaderItems componentsJoinedByString:@"&"];// authorizationHeaderString = [NSString stringWithFormat:@"OAuth %@", authorizationHeaderString];    return authorizationHeaderString;}

使用方法如下:

#pragma mark - 请求方法-(void) connentSign{  //设置食物ID  NSDictionary *params = @{@"food_id" : @"33690"};  //设置请求参数和方法名  [self makeRequestWithMethod:@"food.get" parameters:params completion:^(NSDictionary *data) {      }];  }//开始发送请求- (void) makeRequestWithMethod:(NSString *)method          parameters:(NSDictionary *)params          completion:(void (^)(NSDictionary *data))completionBlock {    NSMutableDictionary *parameters = [params mutableCopy];  [parameters addEntriesFromDictionary:[self defaultParameters]];  [parameters addEntriesFromDictionary:@{ @"method" : method }];    NSString *queryString = [self queryStringFromDictionary:parameters];  NSData *data     = [NSData dataWithBytes:[queryString UTF8String] length:queryString.length];  NSString *authHeader = OAuthorizationHeader([NSURL URLWithString:FAT_SECRET_API_ENDPOINT],                         @"GET",                         data,                         @"9921d3f511a542a8b32b8841bb1d62ed",                         @"f8fa1d96494046c69159099ab153ea1e",                         nil,                         @"");     [self.manager GET:[FAT_SECRET_API_ENDPOINT stringByAppendingFormat:@"?%@", authHeader] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {        NSLog(@"%@",responseObject);      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {      }];  }- (NSDictionary *) defaultParameters {  return @{ @"format": @"json" };}- (NSString *) queryStringFromDictionary:(NSDictionary *)dict {  NSMutableArray *entries = [@[] mutableCopy];    for (NSString *key in dict) {    NSString *value = [dict objectForKey:key];    [entries addObject:[NSString stringWithFormat:@"%@=%@", key, value]];  }    return [entries componentsJoinedByString:@"&"];}

然后我们就可以Happy programming!

 

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

  疑问咨询或技术交流,请加入官方QQ群:JRedu技术交流 (452379712)

 

作者:杰瑞教育
出处:http://www.cnblogs.com/jerehedu/ 
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。