FatSecret Platform API,fatsecretplatform

來源:互聯網
上載者:User

FatSecret Platform API,fatsecretplatform

  在現階段飲食類的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群: (452379712)

 

作者:傑瑞教育
出處:http://www.cnblogs.com/jerehedu/ 
本文著作權歸煙台傑瑞教育科技有限公司和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連,否則保留追究法律責任的權利。 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.