您的当前位置:首页>新品 > 正文

国外开发API,api地址、Authentication认证

来源:CSDN 时间:2023-01-31 08:43:16

在现阶段饮食类的APP发展的非常迅猛,尤其在校园中,学生只需要凭借一个手机就能买到自己想要的食物,真正做到了足不出户。可是如果我们想独立完成一个app就需要有相应的数据支持,这里给大家介绍一个国外的开发API, FatSecret Platform API,这里面包含了许多的食物信息。我们根据这些信息,就能够请求我们的数据,进行独立的app开发。

1、api地址

2、Authentication 认证


(资料图片仅供参考)

这里要注意,Authentication是难点也是重点,下面我们一起研究研究怎么进行认证。

Api中提到,如果我们需要使用api必须首先注册为开发者,并且获取到Consumer KeyandShared Secret,这两个东西。好既然这样我们就开始获取,按照网站注册后如会获取如下数据

有了这个东西我们就可以进行下一步了。继续浏览API的Authentication

看到这我们会发现想要请求api必须还得获取一个signature ,而且上面给我们提供了步骤。好那我们就接着往下看

Step 1. Creating a Signature Base String

意思就是说,我们需要将字段和方法按照顺序拼接出下面的形式,其中的转码我们用的是RFC3986

Step 2. Calculating the Signature value (oauth_signature)

意思是说需要进一步RFC2104和RFC2045和RFC3986进行转码

Step 3. Sending the Request

好,看到这里大家肯定有些模糊,没关系,我们有代码帮助大家理解,上面的api步骤,我通过代码翻译如下

/** *  <#description#> * *  @param url                  请求的地址 *  @param method               请求的方法 *  @param body                 body数据 *  @param _oAuthConsumerKey    申请的key *  @param _oAuthConsumerSecret  申请的Secret *  @param _oAuthToken          暂时用不到 *  @param _oAuthTokenSecret    暂时用不到 * *  @return <#return value=""> */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!

标签:

最新新闻:

新闻放送
Top