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" : @""};
//设置请求参数和方法名
[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的更多相关文章
- Mojo C++ Platform API
Mojo C++ Platform API This document is a subset of the Mojo documentation. Contents Overview Platfor ...
- WeChat Official Account Admin Platform API Introduction
Keyword: WeChat API Introduction Message and GeneralAuthor: PondBay Studio[WeChat Developer EXPERT] ...
- 来自HeroKu的HTTP API 设计指南(中文版)
原文转自:http://get.jobdeer.com/343.get 来自HeroKu的HTTP API 设计指南(中文版) 翻译 by @Easy 简介 本指南中文翻译者为 @Easy ,他是国内 ...
- HTTP API 设计指南(中文版) restfull
http://www.css88.com/archives/5121 目录 基础 总是使用TLS 在Accepts头中带上版本号 通过Etags支持缓存 用Request-Ids追踪请求 用Range ...
- Http API设计
Heroku团队根据heroku platform api和他们自己内部系统的实践经验总结了一些http api设计的准则,发布到了github上. 地址:https://github.com/int ...
- 常用API
1 System类 System类包含一些有用的类和字段.它不能被实例化. 属性和方法都是静态的. 1.1 常见方法 返回以毫秒为单位的当前时间 public static long currentT ...
- HTTP API 设计指南(基础部分)
前言 这篇指南介绍描述了 HTTP+JSON API 的一种设计模式,最初摘录整理自 Heroku 平台的 API 设计指引 Heroku 平台 API 指引. 这篇指南除了详细介绍现有的 API 外 ...
- Unity 游戏框架搭建 (二十三) 重构小工具 Platform
在日常开发中,我们经常遇到或者写出这样的代码 var sTrAngeNamingVariable = "a variable"; #if UNITY_IOS || UNITY_AN ...
- HTTP API 设计指南
本指南描述了一系列 HTTP+JSON API 的设计实践, 来自并展开于 Heroku Platform API 的工作.本指南指导着Heroku内部API的开发,我们希望也能对Heroku以外的A ...
随机推荐
- VMware虚拟机VMware Authorization Service不能启动问题
出现VMware Authorization Service不能启动问题,注意要在安装VMware Player时使用管理员权限
- mysql打印输出转csv格式
1. mysql打印输出放在input.csv中 2. 执行该文件 <?php $str = file_get_contents("./input.csv"); $str = ...
- (13) go map
1.定义 map 无序, key唯一 (1) (2) (3)定义+赋值 2. map的值时map, 记得要make 3.增删改查 (1)增 改 (2)删除 (3)查 4.遍历 值map 嵌套for, ...
- Coding.net进阶,使用Git管理代码
原文来自:http://conw.net/archives/18/ (我自己的博客,点击链接查看文章最新版本) Git是目前最流行的版本控制系统,这里以GitHub为例,介绍git的基本使用. Git ...
- 哈尔滨理工大学第七届程序设计竞赛决赛(网络赛-高年级组)I - 没有名字
题目描述 tabris实在是太菜了,没打败恶龙,在绿岛也只捡到一块生铁回去了,为了不在继续拉低acimo星球的平均水平逃离地球,来到了Sabi星球. 在这里tabris发现了一种神奇的生物,这种生物不 ...
- Python并发编程-生产消费模型
生产消费模型初步 #产生两个子进程,Queue可以在子进程之间传递消息 from multiprocessing import Queue,Process import random import t ...
- iTerm2配置
1.颜色Solarized 首先下载 Solarized: $ git clone git://github.com/altercation/solarized.git Terminal/iTerm2 ...
- 【BZOJ 3812】 3812: 主旋律 (容斥原理**)
3812: 主旋律 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 235 Solved: 196 Description 响应主旋律的号召,大家决定 ...
- PHP 笔记——String 字符串
1. 定义 单引号括起来的字符串被原样输出. 双引号字符串中的变量被PHP解析为变量值. 2. 获取字符串长度 strlen(string $string): int 在utf-8下,汉字占3个字符, ...
- NOIP2018提高组题解
D1T1:铺设道路 回忆NOIP2013D2T1 积木大赛,发现这两题唯一的区别就是一个是造山一个是填坑,而把填坑的操作反序就是造山,所以可以直接使用那道题的方法. 具体方法是,从左到右每次考虑新的一 ...