Java 实现在线翻译功能 调用微软Bing API
Java封装的百度翻译Api
http://www.pocketdigi.com/20130626/1123.html
百度没有提供直接可用的翻译api,有道倒是有,不过只能英译中,不支持其他语言。但是百度自己有个翻译服务,http://fanyi.baidu.com/,使用的时候,页面并不会刷新,而是用ajax调用了一个翻译API,分析了一下,这个api地址是http://fanyi.baidu.com/transapi,接受三个参数,from,to,query分别是源语言,目标语言,待翻译文本。
简单封装了一下,默认中译英,要改其他语言,可以把参数提出来:
package com.pocketdigi.english; import java.net.URLEncoder; import model.TranslateMode; import com.google.gson.Gson;import common.HttpGet; public class TranslateApi { /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub String dst=translate("百度翻译API测试");System.out.println(dst); }public static String translate(String source){String api_url;try {api_url = new StringBuilder("http://fanyi.baidu.com/transapi?from=zh&to=en&query=").append(URLEncoder.encode(source,"utf-8")).toString();String json=HttpGet.getHtml(api_url, "utf-8");Gson gson=new Gson();TranslateMode translateMode=gson.fromJson(json, TranslateMode.class); if(translateMode!=null&&translateMode.getData()!=null&&translateMode.getData().size()==1){return translateMode.getData().get(0).getDst();}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;} }
package model; import java.util.List; public class TranslateMode {String from,to;List<Data> data;public class Data{String dst,src; public String getDst() {return dst;} public void setDst(String dst) {this.dst = dst;} public String getSrc() {return src;} public void setSrc(String src) {this.src = src;} }public String getFrom() {return from;}public void setFrom(String from) {this.from = from;}public String getTo() {return to;}public void setTo(String to) {this.to = to;}public List<Data> getData() {return data;}public void setData(List<Data> data) {this.data = data;} }
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import java.util.List;import java.util.Map;public class YoudaoTranslate { private String url = "http://fanyi.youdao.com/openapi.do"; private String keyfrom = ""; private String key = ""; private String doctype = "xml"; private String sendGet(String str) { // 编码成UTF-8 try { str =URLEncoder.encode(str, "utf-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } StringBuffer buf = newStringBuffer(); buf.append("keyfrom="); buf.append(keyfrom); buf.append("&key="); buf.append(key); buf.append("&type=data&doctype="); buf.append(doctype); buf.append("&version=1.1&q="); buf.append(str); String param =buf.toString(); String result = ""; BufferedReader in = null; try { StringurlName = url + "?" + param; URL realUrl =new URL(urlName); //打开和URL之间的连接 URLConnectionconn = realUrl.openConnection(); //设置通用的请求属性 //conn.setRequestProperty("accept", "* public String getYouDaoValue(String str) { String result = null; // 发送GET请求翻译 result = sendGet(str); // 处理XML中的值 int re1 =result.indexOf("<errorCode>"); int re2 =result.indexOf("</errorCode>"); String in =result.substring(re1 + 11, re2); System.out.println("===========翻译是否成功============"+ in); if (in.equals("0")) { System.out.println("翻译正常"); re1 =result.indexOf("<paragraph><![CDATA["); re2 =result.indexOf("]]></paragraph>"); in =result.substring(re1 + 20, re2); System.out.println("==========有道翻译================"+ in); re1 =result.indexOf("<ex><![CDATA["); re2 =result.indexOf("]]></ex>"); in =result.substring(re1 + 13, re2); System.out.println("==========有道词典-网络释义================"+ in); } else if (in.equals("20")){ System.out.println("要翻译的文本过长"); return"要翻译的文本过长"; } else if (in.equals("30")){ System.out.println("无法进行有效的翻译"); return"无法进行有效的翻译"; } else if (in.equals("40")){ System.out.println("不支持的语言类型"); return"不支持的语言类型"; } else if (in.equals("50")){ System.out.println("无效的key"); return"无效的key"; } return result; } public static void main(String[] args) { String str = "The weather isgood today"; YoudaoTranslate test = newYoudaoTranslate(); String temp =test.getYouDaoValue(str); System.out.println(temp); }}
package com.test; import com.memetix.mst.language.Language; import com.memetix.mst.translate.Translate; public class Test { public static void main(String[] args) { /* * 大概是针对C#和php的,没有仔细研究过(可以访问下方的http://msdn.microsoft.com/en-us/library/hh454950.aspx 来学习一下) * Set your Windows Azure Marketplace client info - See http://msdn.microsoft.com/en-us/library/hh454950.aspx Translate.setClientId( Enter your Windows Azure Client Id here ); Translate.setClientSecret( Enter your Windows Azure Client Secret here ); */ //在Java程序内翻译 Translate.setKey( Enter your API Key here ); String translatedText; try { String content = "Bayside Living, Great Value for Money. " + "Open 11am - 11.30am Saturday 23rd March, 2013. Occupying a level 814m2 parcel in one of the areas great family friendly pockets." + " This two storey family home is ,spaciously proportioned, wonderfully quiet and ready to enjoy immediately. " + "Interiors provide a flexible layout and superb in/outdoor flow to the child friendly ,entertaining areas, catching abundant north easterly sunshine. " + "The upper level captures views reaching to Moreton Bay and beyond, whilst letting the natural light fill the home." + "The floor plan can be adapted to suit the occasion, as it offers multiple formal and casual living and dining areas and enough accommodation to cater for the family. " + "The large central kitchen overlooks the level, child friendly lawn and landscaped gardens, featuring a covered patio that’s perfect for entertaining guests. " + "All bedrooms are sizable with built ins and the dedicated parents retreat features an ensuite and large covered front deck with Bay views and privacy shutters. " + "Also featuring a double lock up garage with internal access, plenty of storage and optional parking in the drive way. " + "For the astute buyer/investor, the home offers a 22m frontage and has the option of being sub divided(Subject to Brisbane City Council Approval)This desirable location has easy access to buses, trains, cafés and restaurants, with the Gateway, Airport and Port of Brisbane a short drive away." + " Those seeking the highly sought after bayside lifestyle need look no further than this outstanding home. Owners are committed elsewhere and will consider genuine offers."; translatedText = Translate.execute(content, Language.ENGLISH, Language.CHINESE_SIMPLIFIED); System.out.println(translatedText); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }