The open interface document of Baidu Translator is here: Http://api.fanyi.baidu.com/api/trans/product/apidoc
As for the application key what is not said, directly into the realization.
I did it with HC4.5.1, which is a bit inconsistent with the 3 4 version in part of the code processing.
public static void Main (string[] args) {String query = "Make a mistake"; Get (query); Post (query); }private static void Get (String query) {closeablehttpclient HC = Httpclientbuilder.create (). build (); HttpGet httpget = new HttpGet (); Closeablehttpresponse response;try {String q = urlencoder.encode (query, "UTF-8"); String from = Lang.auto; String to = Lang.en; string salt = randomstringutils.randomnumeric (8);//appid+q+salt+ key String sign = Encryptutils.md5crypt ( Translateapi.appid + query + salt + translateapi.key) HttpGet = new HttpGet (Translateapi.url + "? q=" + q + "&from=" + from+ "&to=" + to+ "&appid=" + translateapi.appid+ "&salt=" + salt+ "&sign=" + sign); response = Hc.execute (HttpGet); System.out.println (Entityutils.tostring (Response.getentity ()));} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally { Httpget.releaseconnection ();}} private static void post (String query) {closeablehttpclient HC = HttpclienTbuilder.create (). build (); HttpPost HttpPost = new HttpPost (Translateapi.url); Closeablehttpresponse Response;try {string salt = randomstringutils.randomnumeric (8);//appid+q+salt+ Key String sign = Encryptutils.md5crypt (translateapi.appid + query + salt + translateapi.key); list<namevaluepair> params = new arraylist<namevaluepair> (); Params.add (New Basicnamevaluepair ("Q", query));p Arams.add (New Basicnamevaluepair ("from", Lang.auto));p Arams.add ( New Basicnamevaluepair ("to", Lang.en));p Arams.add (New Basicnamevaluepair ("AppID", Translateapi.appid));p Arams.add ( New Basicnamevaluepair ("salt", salt));p Arams.add (New Basicnamevaluepair ("sign"); Httppost.setentity (new Urlencodedformentity (params, "UTF-8")); response = Hc.execute (HttpPost); System.out.println (Entityutils.tostring (Response.getentity ()));} catch (Clientprotocolexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally { Httppost.releaseconnection ();} }
The whole process is actually relatively simple, a little attention point, is the use of post method, because it is used post, so the Q parameter is essentially the original value, rather than the value after UrlEncode. If you pass the encoded value, then congratulations, the result you want is not the same thing at all. Another key point is that when the post parameter is added to the POST request, it must pass the UTF-8 format parameter in the past, otherwise, the message will be reported with sign error.
Baidu translation Open Interface Java implementation