如何在NSURLSession中传递Windows Azure Marketplace帐户密钥?

时间:2015-11-24 17:56:22

标签: windows azure authentication nsurlsession azure-marketplace

我已使用以下代码在“Google搜索”上成功执行图像查询:

NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"]; 
NSString * escapedValue = [searchKeys stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * urlString = [[NSString alloc] initWithFormat:@"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%@", escapedValue];
NSURL *JSONURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];

NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] 
dataTaskWithRequest:request
    completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {                                    

NSDictionary *googleResult = [NSJSONSerialization JSONObjectWithData:data 
           options:NSJSONReadingMutableContainers
           error:nil];

// PROCESS GOOGLE RESULTS HERE...
}];

[dataTask resume];

......直到Google决定限制访问权限。 现在,我想与Microsoft Bing实现相同的功能! (Windows Azure Marketplace)。 我已获得帐户密钥(每月可获得5000次免费搜索)。

我知道我必须将帐户密钥作为请求的一部分传递。

如何更改代码以实现此目的?

2 个答案:

答案 0 :(得分:0)

如果是GET请求,您只需在URL字符串末尾添加另一个查询,但如果是POST请求则可以使用

NSString *constructedParam = @"key=value&key=value";
NSData *parameterData = [constructedParam dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[request addValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:parameterData]

答案 1 :(得分:0)

感谢。在阅读了Microsoft的一些文档后,我能够解决这个问题。这是必需的代码:

// Method required to encode data...
-(NSString *)stringByEncodingInBase64:(NSData *)data
{
    NSUInteger length = [data length];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithLength:((length + 2) / 3) * 4];


uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];

for (NSUInteger i = 0; i < length; i += 3)
{
    NSUInteger value = 0;
    for (NSUInteger j = i; j < (i + 3); j++)
    {
        value <<= 8;
        if (j < length)
        {
            value |= (0xFF & input[j]);
        }
    }

    static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    NSUInteger idx = (i / 3) * 4;
    output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
    output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
    output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6)  & 0x3F] : '=';
    output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0)  & 0x3F] : '=';
}

return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}

以下是获取搜索结果的代码:

NSData *authData;
NSString *authKey = @"<ENTER Windows Azure Marketplace Account KEY HERE>";
        NSLog (@"authkey:%@",authKey);
        authData = [[[NSString alloc] initWithFormat:@"%@:%@", authKey, authKey] dataUsingEncoding:NSUTF8StringEncoding];
        NSString *authValue = [[NSString alloc] initWithFormat:@"Basic %@", [self stringByEncodingInBase64:authData]];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    [config setHTTPAdditionalHeaders:@{@"Authorization": authValue}];


    NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
    URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
    [URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"]; // %26, %3D, %3F
    NSString * escapedValue = [<ENTER SEARCH CRITERIA HERE> stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
    NSString * urlString = [[NSString alloc] initWithFormat:@"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='%@'&$top=50&$format=json", escapedValue];
    NSURL *JSONURL = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
    NSURLSessionDataTask * dataTask = [[NSURLSession sessionWithConfiguration:config] dataTaskWithRequest:request  
                                completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if(data == nil){
            // Process failure here.
        }

        NSDictionary *resultadoCompleto = [NSJSONSerialization JSONObjectWithData:data
                                                                          options:NSJSONReadingMutableContainers
                                                                            error:nil];

       // PROCESS BING! RESULTS HERE...

     }];

[dataTask resume];

resultadoCompleto显示完整的结果!