IOS Baidu Translation API interface implementation effect

Source: Internet
Author: User
Tags md5 encryption

Yesterday received several new tasks, the first one is to implement the text translation function. Search data from the Internet to find commonly used there are Baidu translation, Youdao translation, Google translation.

All three are in contrast: 1. Baidu 2 million characters per month free

2. Youdao fee, initial send 100 yuan experience gold

3. Google Translate pure English documents.

Comprehensive consideration, Baidu translation free, support language more, decided to use Baidu translation.

Pre-preparation is roughly the same, registration account, application AppID and key. An account can only request an ID, if you have more than one app that requires multiple accounts to apply.

Pre-preparation Skip, look at the document on it.

There are not many documents and there is no OC version.

Baidu provides the interface for network requests and returns the translation results. The document says you can post with get and I use get.

Parameters that must be written to the interface:

Q: The text to be translated;

From: To be translated text language

To: Target language

APPID: Application of the APPID

Salt: Random number, not detailed in the document, I see from other people on the Internet that I can use the random number provided in the document, guessing that it may be as long as the 10-digit number can be, but I did not go to verify that the document is still available with random numbers.

Sign: signature; According to the document, will Appid,q,salt, key stitching, after utf-8 encoding, and then MD5 encryption, get the signature.

The text to be translated requires UTF-8 encoding because if the text to be translated is Chinese, the network request does not support Chinese, and the text needs to be UTF-8 encoded.

But as I went through the document, there were several problems:

1. Only single English words can be translated and English sentences cannot be translated.

2. It is not possible to translate Chinese into English.

The error code is a 54001:sign (signed) error.

I have been stuck here for a long time and have no idea where the mistake is.

After referring to a blog post, I found the problem.

This is how the signature is generated in the document: "Compute the signature sign (MD5 encryption for string 1, note that string 1 must be UTF-8 encoded before calculating MD5)"

But this sentence is not entirely correct.

The string 1 here is the result of concatenation of the Appid,q,salt and keys, followed by the UTF-8 encoding of the document and then MD5 encryption.

The most important:

Encoding: We used stringbyaddingpercentescapesusingencoding for UTF-8 encoding before iOS9, but this method was discarded in iOS10. So which method would you use to encode it?

If you use the old method to encode, the problem is solved, and the two problems I met are solved.

If you use the new method to encode, I am sorry, you will encounter the problems I encountered.

So we can only use the old method, after all, has been abandoned.

Then I tried a situation and found that it was OK. That is: string 1 does not utf-8 encoding, direct encryption, of course, the request Utf-8 encoding is necessary. After this operation, the problem is solved.

So, after stitching, completely without utf-8 encoding, direct encryption can be. Even if the text you are translating is Chinese.

This function mainly referred to two blog, thank you very much. What is wrong in the blog, please do not hesitate to enlighten.

Click to open the link

Click to open the link

The following is the complete request code:

 _inputtext = _inputtextview.text;
    
    
    
    _inputtext = @ "Today is a fine day";
  
    Baidu API NSString *httpstr = @ "Https://fanyi-api.baidu.com/api/trans/vip/translate"; AppID q Salt Key stitching together nsstring *appendstr = [NSString stringwithformat:@ "%@%@%@%@", Kbaidutranslationappid,_inputtex
    
    T,kbaidutranslationsalt,kbaidutranslationkey];
  
The string after stitching is utf-8 transcoding//[appendstr stringbyremovingpercentencoding:[nscharacterset Urlqueryallowedcharacterset]];
  NSString *appendencoding = [Appendstr stringbyremovingpercentencoding];
NSString *appendencoding = [Appendstr stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding];
    NSLog (@ "&&&&&&&%@", appendstr);
    
    Cryptographic generation signature NSString *md5str = [self md5:appendencoding]; The text model to be translated urf-8 transcoding nsstring *qencoding = [_inputtext stringbyaddingpercentencodingwithallowedcharacters:[
    
    Nscharacterset Urlqueryallowedcharacterset]]; NSString using GET Request *URLSTR = [NSString stringwithformat:@ "%@?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",
    
    httpstr,qencoding,@ "Auto", @ "en", kbaidutranslationappid,kbaidutranslationsalt,md5str];
    Afhttpsessionmanager *manager = [Afhttpsessionmanager manager];
    Add common parameters [Manager.requestserializer willchangevalueforkey:@ "timeOutInterval"];
    Manager.requestSerializer.timeoutInterval = 20.F;
    
    [Manager.requestserializer didchangevalueforkey:@ "timeOutInterval"]; [Manager get:urlstr Parameters:nil Progress:nil success:^ (nsurlsessiondatatask * _nonnull task, id _nullable RESPONSEOBJ
            
        ECT) {if (Responseobject = = nil) {return;
        //Get the translated string nsstring *resstr = [[Responseobject objectforkey:@ "Trans_result"] firstobject][@ "DST"];
        
    Self.outputTextView.text = Resstr;
     } failure:^ (Nsurlsessiondatatask * _nullable task, Nserror * _nonnull error) {}];

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.