在现阶段饮食类的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" : @""};
//设置请求参数和方法名
[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群: (452379712)

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

FatSecret Platform API的更多相关文章

  1. Mojo C++ Platform API

    Mojo C++ Platform API This document is a subset of the Mojo documentation. Contents Overview Platfor ...

  2. WeChat Official Account Admin Platform API Introduction

    Keyword: WeChat API Introduction Message and GeneralAuthor: PondBay Studio[WeChat Developer EXPERT] ...

  3. 来自HeroKu的HTTP API 设计指南(中文版)

    原文转自:http://get.jobdeer.com/343.get 来自HeroKu的HTTP API 设计指南(中文版) 翻译 by @Easy 简介 本指南中文翻译者为 @Easy ,他是国内 ...

  4. HTTP API 设计指南(中文版) restfull

    http://www.css88.com/archives/5121 目录 基础 总是使用TLS 在Accepts头中带上版本号 通过Etags支持缓存 用Request-Ids追踪请求 用Range ...

  5. Http API设计

    Heroku团队根据heroku platform api和他们自己内部系统的实践经验总结了一些http api设计的准则,发布到了github上. 地址:https://github.com/int ...

  6. 常用API

    1 System类 System类包含一些有用的类和字段.它不能被实例化. 属性和方法都是静态的. 1.1 常见方法 返回以毫秒为单位的当前时间 public static long currentT ...

  7. HTTP API 设计指南(基础部分)

    前言 这篇指南介绍描述了 HTTP+JSON API 的一种设计模式,最初摘录整理自 Heroku 平台的 API 设计指引 Heroku 平台 API 指引. 这篇指南除了详细介绍现有的 API 外 ...

  8. Unity 游戏框架搭建 (二十三) 重构小工具 Platform

    在日常开发中,我们经常遇到或者写出这样的代码 var sTrAngeNamingVariable = "a variable"; #if UNITY_IOS || UNITY_AN ...

  9. HTTP API 设计指南

    本指南描述了一系列 HTTP+JSON API 的设计实践, 来自并展开于 Heroku Platform API 的工作.本指南指导着Heroku内部API的开发,我们希望也能对Heroku以外的A ...

随机推荐

  1. SQL join关键字

    如果一张表有很多个字段可能填入起来十分的困难复杂,不如把它拆分成两个表,然后查看的时候合并起来. 比如我要记录学生的姓名,班级,成绩,父母的电话号码,那么我们可以创建一个表1 储存学生的姓名班级成绩, ...

  2. Jquery操作select标签的常用方法

    <select id="search"> <option value='1'>baidu</option> <option value=' ...

  3. y450 archlinux cuda6.5

    y450 archlinux cuda6.5 January 28, 2018 4:11 PM archlinux是最新更新版本,gcc版本到了7.几,太新了. [qiangge@lqspc ~]$ ...

  4. iOS 9应用开发基础教程下册

    iOS 9应用开发基础教程下册   介绍: 本教程是国内第一本iOS 9开发应用教程.本教程基于Xcode 7.0,使用Swift 2.0语言讲解如何开发iOS 9的应用App. 学习建议:本教程针对 ...

  5. Vue 2.0学习(六)内置指令

    基本指令 1.v-cloak v-cloak不需要表达式,它会在Vue实例结束编译时从绑定的HTML元素上移除,经常和CSS的display:none配合使用. <div id="ap ...

  6. Wannafly挑战赛17 B

    题解 大概就是求证这个 \[\sum_i^nC_{n}^i*C_n^i = C_{2n}^n\] 证明: \[(1+x)^{2n} = [C(0,n)+C(1,n)*x+...+C(n,n)*x^n] ...

  7. 「TJOI 2018」教科书般的亵渎

    「TJOI 2018」教科书般的亵渎 题目描述 小豆喜欢玩游戏,现在他在玩一个游戏遇到这样的场面,每个怪的血量为 \(a_i\) ,且每个怪物血量均不相同, 小豆手里有无限张"亵渎" ...

  8. BZOJ 4036: [HAOI2015]按位或 集合幂函数 莫比乌斯变换 莫比乌斯反演

    http://www.lydsy.com/JudgeOnline/problem.php?id=4036 http://blog.csdn.net/lych_cys/article/details/5 ...

  9. 【BZOJ】4709: [Jsoi2011]柠檬

    4709: [Jsoi2011]柠檬 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 779  Solved: 310[Submit][Status][ ...

  10. 内功心法 -- java.util.LinkedList<E> (5)

    写在前面的话:读书破万卷,编码如有神--------------------------------------------------------------------下文主要对java.util ...