Bing Translator错误 - 'to'必须是有效的语言

时间:2013-11-25 17:35:09

标签: objective-c bing-api

这是我调用api的方法:

  + (NSString*)bingTranslator:(NSString*)word from:(NSString*)fromLanguage to:(NSString*)toLanguage{


    NSString* token = [PAPUtility bingTranslatorGetToken];

    if (token) {

        NSString* authToken = [@"Bearer " stringByAppendingString:token];

        NSMutableString* authHeader = [NSMutableString stringWithString:@"text="];        

        [authHeader appendString:word];
        [authHeader appendString:@"&to="];
        [authHeader appendString:toLanguage];
        [authHeader appendString:@"&from="];
        [authHeader appendString:fromLanguage];

        NSMutableURLRequest *request =[NSMutableURLRequest
                                       requestWithURL:[NSURL URLWithString:kWSBingTranslatorURL]
                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                       timeoutInterval:60.0];


        [request setHTTPMethod:@"POST"];
        [request addValue:authToken
        forHTTPHeaderField:@"Authorization"];

        const char *bytes = [authHeader UTF8String];
        [request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];


        NSLog(@"word = %@",word);
        NSLog(@"fromLanguage = %@",fromLanguage);
        NSLog(@"toLanguage = %@",toLanguage);
        NSLog(@"authHeader = %@",authHeader);
        NSLog(@"request.URL = %@", request.URL);


        NSURLResponse* response;
        NSError* error;

        NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        if (data != nil) {
            NSString* contents = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
            NSString *formattedContents = [contents stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            NSLog(@"formattedContents = %@", formattedContents);

            return formattedContents; 
        }

        return nil;
    }
    return nil;

}

以下是生成的日志语句:

2013-11-25 09:28:52.857 WSPhoto[73703:c07] word = azucarera
2013-11-25 09:28:52.858 WSPhoto[73703:c07] fromLanguage = es
2013-11-25 09:28:52.858 WSPhoto[73703:c07] toLanguage = en
2013-11-25 09:28:57.298 WSPhoto[73703:c07] authHeader = text=azucarera&to=en&from=es
2013-11-25 09:28:57.300 WSPhoto[73703:c07] request.URL = http://api.microsofttranslator.com/v2/Http.svc/Translate?

错误日志:

2013-11-25 09:28:57.557 WSPhoto[73703:c07] formattedContents = <html><body><h1>Argument Exception</h1><p>Method: Translate()</p><p>Parameter: to</p><p>Message: 'to' must be a valid language
Parameter name: to</p><code></code><p>message id=3811.V2_Rest.Translate.3F972A8E</p></body></html>

'to'参数记录为en,该参数有效。我已经尝试将其更改为其他语言,例如de,但具有相同的错误。我不明白,似乎还有其他事情发生。

1 个答案:

答案 0 :(得分:0)

哇,哇。自从我出生以来,我并没有感到沮丧。在我解决了原来的错误后,我又弹出了4个以上的错误,但现在它终于正常工作了。我将在这里留下两种方法来获取令牌然后翻译。

+ (NSString*)bingTranslatorGetToken{


    // URL Encode client secret
    NSString *clientSecret = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                                                          (CFStringRef)kWSBingTranslatorClientSecret,
                                                                                          NULL,
                                                                                          (CFStringRef) @"!*'();:@&=+$,/?%#[]",
                                                                                          kCFStringEncodingUTF8);
    NSMutableString* authHeader = [NSMutableString stringWithString:@"client_id="];
    [authHeader appendString:kWSBingTranslatorClientID];
    [authHeader appendString:@"&client_secret="];
    [authHeader appendString:clientSecret];
    [authHeader appendString:@"&grant_type=client_credentials&scope=http://api.microsofttranslator.com"];



    NSMutableURLRequest *request =[NSMutableURLRequest
                                   requestWithURL:[NSURL URLWithString:kWSBingTranslatorTokenURL]
                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                   timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded"
    forHTTPHeaderField:@"Content-Type"];

    const char *bytes = [authHeader UTF8String];
    [request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];

    NSURLResponse* response;
    NSError* error;

    NSData* data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];


    if (data != nil) {

        // Get the access_token object from data
        NSDictionary* json = [NSJSONSerialization
                              JSONObjectWithData:data

                              options:kNilOptions
                              error:&error];

        NSString* accessToken = [json objectForKey:@"access_token"];

        return accessToken;
    }



    return nil;
}

+ (NSString*)bingTranslator:(NSString*)word from:(NSString*)fromLanguage to:(NSString*)toLanguage{

    NSString* token = [PAPUtility bingTranslatorGetToken];

    if (token) {

        NSString* authToken = [@"Bearer " stringByAppendingString:token];

        NSMutableString* authHeader = [NSMutableString stringWithString:@"text="];

        [authHeader appendString:word];
        [authHeader appendString:@"&from="];
        [authHeader appendString:fromLanguage];
        [authHeader appendString:@"&to="];
        [authHeader appendString:toLanguage];
        [authHeader appendString:@"&contentType="];
        [authHeader appendString:@"text/plain"];

        NSString* urlString = [kWSBingTranslatorURL stringByAppendingString:authHeader];

        // EDIT -- Needed to add this line to escape accents
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

        NSMutableURLRequest *request =[NSMutableURLRequest
                                       requestWithURL:[NSURL URLWithString:urlString]
                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                       timeoutInterval:60.0];


        [request setHTTPMethod:@"GET"];
        [request addValue:authToken
        forHTTPHeaderField:@"Authorization"];


        NSURLResponse* response;
        NSError* error;

        NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        if (data != nil) {
            NSString* contents = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

            // An NSString category
            contents = [contents stringByStrippingHTML];

            return contents;
        }

        return nil;
    }
    return nil;

}