At this stage of the development of food applications is very rapid, especially in the campus, students only need to rely on a mobile phone to buy their own food, really do not stay home. However, if we want to complete an app independently need to have the corresponding data support, here to introduce a foreign development API, Fatsecret Platform API, which contains a lot of food information. Based on this information, we are able to request our data for independent app development.
1. API Address
Http://platform.fatsecret.com/api/Default.aspx?screen=rapih
2, authentication certification
Here to notice,authentication is the difficulty is also the focus, below we study together how to carry out certification.
Note that you must is signed up as a developer, and agree to our Terms of Service on order to obtain you Consumer key< /c5> andgkfx Secret, which you'll need to send requests to the REST API.
The API mentions that if we need to use the API we must first register as a developer and get to Consumer Key andShared Secret, which are two things. Well, in that case, we will start to obtain, according to the website registration, if you will get the following data
With this thing we can proceed to the next step. Continue browsing the API authentication
Seeing this we will find that we need to get a signature to request the API, and we have provided the steps above. Okay, so let's go down and look.
Step 1. Creating a Signature Base String
This means that we need to stitch the fields and methods together in the following form, with the transcoding we use 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)
It means that further RFC2104 and RFC2045 and RFC3986 are needed for transcoding.
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 Str ING, with the inclusion of the oauth_signature.
That ' s it! We'll hopefully be able to generate the same oauth_signature from our end and confirm it's indeed you
Well, see here everyone must be a little vague, okay, we have code to help you understand, above the API steps, I translated by Code as follows
/** * < #Description #> * * @param URL Request Address * @param method request * @param body Body Data * @param _oauthconsumerkey Application key * @param _oauthconsumersecret application secret * @param _oauthtoken Temporarily do not use * @param _oauthtokensecret temporarily do not use * * @return < #return value description#> */nsstring *oauthoriz Ationheader (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, [EncodedPara Meters 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], [u RL 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 stringwit hformat:@ "%@=%@", [Key ab_rfc3986encodedstring], [Value ab_rfc3986encodedstring]]; }//PARKER change:changed concatentation string from ', ' to ' & ' nsstring *authorizationheaderstring = [au Thorizationheaderitems componentsjoinedbystring:@ "&"];//authorizationheaderstring = [NSString stringWithFormat : @ "OAuth%@", authorizationheaderstring]; return authorizationheaderstring;}
Use the following method:
#pragma mark-Request Method-(void) connentsign{//Set food id nsdictionary *params = @{@ "food_id": @ "33690"}; Set request parameter and method name [self makerequestwithmethod:@ "food.get" Parameters:params completion:^ (Nsdictionary *data) {}] ; }//Start sending request-(void) Makerequestwithmethod: (NSString *) method parameters: (Nsdictionary *) params Completion: (void (^) (nsdictionary *data)) Completionblock {nsmutabledictionary *parameters = [params mutab Lecopy]; [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:@]& "];}
And then we can happy programming!.
To learn more about the small partners, you can click to view the source code , run the test yourself.
Inquiries or technical exchanges, please join the official QQ Group: (452379712)
Jerry Education
Source:http://www.cnblogs.com/jerehedu/
This article is the copyright of Yantai Jerry Education Technology Co., Ltd. and CSDN Common, welcome reprint, but without the author's consent must retain this paragraph statement, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fatsecret Platform API