在現階段飲食類的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:@"&"];}
疑問咨詢或技術交流,請加入官方QQ群: (452379712)
|
新聞熱點
疑難解答