0

我已經成功地執行在「谷歌搜索」圖片查詢用下面的代碼:如何將Windows Azure市場帳戶密鑰傳遞給NSURLSession?

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]; 

...直到谷歌決定限制訪問。 現在,我想實現與微軟Bing一樣! (Windows Azure市場)。 我已經獲得帳戶密鑰(每月可獲得5000次免費搜索)。

我知道我必須通過帳戶密鑰作爲請求的一部分。

如何更改我的代碼以實現此目的?

回答

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] 
0

感謝。在閱讀了微軟的一些文檔後,我能夠解決這個問題。這是需要的代碼:

// 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[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

    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顯示了完整的結果!

相關問題