0

我已使用以下代码在“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];

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

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

我怎样才能改变我的代码来实现这个?

4

2 回答 2

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[] = "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 显示完整的结果!

于 2015-11-26T16:46:18.863 回答
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]
于 2015-11-24T20:57:35.507 回答