在现阶段饮食类的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. Java经典设计模式之七大结构型模式

    转载: Java经典设计模式之七大结构型模式 博主在大三的时候有上过设计模式这一门课,但是当时很多都基本没有听懂,重点是也没有细听,因为觉得没什么卵用,硬是要搞那么复杂干嘛.因此设计模式建议工作半年以 ...

  2. codeforces-727A

    题目连接:http://codeforces.com/contest/727/problem/A A. Transformation: from A to B time limit per test ...

  3. SpringMVC框架 注解 (转)

    原文地址:http://www.cnblogs.com/yjq520/p/6734422.html 1.@Controller @Controller 用于标记在一个类上,使用它标记的类就是一个Spr ...

  4. 【BZOJ 3560】 3560: DZY Loves Math V (欧拉函数)

    3560: DZY Loves Math V Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 241  Solved: 133 Description ...

  5. 【lct】poj2763 Housewife Wind

    题意:给你一棵树,边带权,支持两种操作:修改某条边的权值:查询两点之间的最短路. lct主要实现单点修改和路径和. 修改x结点的值只需将x Splay到其所在辅助树的根,然后修改其值,再maintai ...

  6. Map按照数值进行排序

    public static Map<String, Integer> sortMapByValue(Map<String, Integer> oriMap) { if (ori ...

  7. 使用 dsc_extractor 导出 dyld_shared_cache_arm64

    iOS系统的全部Framework二进制被打包成一个cache文件,位于 /System/Library/Caches/com.apple.dyld 目录下,我们要想查看某个系统库的二进制需要将 dy ...

  8. Git与SVN

    http://www.nowamagic.net/academy/detail/48160207 前面提到,Linus一直痛恨CVS及SVN这些集中式的版本控制系统,为什么呢?Git是分布式版本控制系 ...

  9. 利用BusyBox ~私人定制 My LINUX~

    前言 我在今天在这里跟大家详细地探讨一下Linux系统的定制过程和实现例如.用户能够远程登录:和Nginx能够稳定地运行在我们私人定制的LINUX系统上.一步一步从头开始定制属于我们自己的系统. 正文 ...

  10. JS 判断PC、android、ios、微信浏览器

    1.通过js userAgent来判断 <h1>判断访问此链接的操作系统</h1> <script> var Agents = new Array("An ...