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 block
			e.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;
	}
 
}





Java 调用 有道翻译API
http://www.abigdreamer.com/programming/swing/the-proper-way-to-translate-officially-free-open-translation-api.html
http://fanyi.youdao.com/openapi?path=data-mode申请key和id
数据接口
http://fanyi.youdao.com/openapi.do?keyfrom=xxx&key=yyyy&type=data&doctype=<doctype>&version=1.1&q=要翻译的文本
版本:1.1,请求方式:get,编码方式:utf-8
主要功能:中英互译,同时获得有道翻译结果和有道词典结果(可能没有)
参数说明:
 type - 返回结果的类型,固定为data
 doctype - 返回结果的数据格式,xml或json或jsonp
 version - 版本,当前最新版本为1.1
 q - 要翻译的文本,不能超过200个字符,需要使用utf-8编码
errorCode:
 0 - 正常
 20 - 要翻译的文本过长
 30 - 无法进行有效的翻译
 40 - 不支持的语言类型
 50 - 无效的key

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);
 }
}




Java 实现在线翻译功能 调用微软Bing API
http://blog.csdn.net/zhouleiblog/article/details/8749588
下面是利用java程序实现翻译功能,调用微软Bing API
注意:代码中的keyId 需要自己申请。。。
(1)首先去 http://code.google.com/p/microsoft-translator-java-api/,下载相关jar文件,这里有对微软翻译api的详细使用有作详细介绍。
(2)去申请key,进入 http://www.bing.com/developers/createapp.aspx,填写相关的你的应用信息就行了。就会有下面的图片中显示的key,中的Application ID就是key
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();  
            }  
  
             
            
    }  
  
}
 

翻译结果:
湾畔生活,物超所值。打开 11 上午-11:30 上午星期六 2013 年 3 月 23 日。中的一个伟大的家庭友好口袋领域占领级别 814 米 2 的包裹。这两个层高家是,宽敞的比例、 奇妙安静和准备立即享受。室内设计提供一个灵活的布局和精湛的中、 户外流动对儿童友好,娱乐领域,捕捉北偏东阳光充沛。上层捕获达成到莫顿湾和之外,同时又让自然的浅色填充在家庭的观点。平面图可以调整,以适合各种场合,它提供了多个正式和休闲生活和就餐区及足够的住宿以照顾家庭。大型中央厨房俯瞰级别、 儿童友好草坪和花园,设有盖的天井,非常适合招待客人。所有的卧室都相当具有内置的加载项和专用的父母撤退套间和大盖的前甲板与海湾美景和隐私百叶窗的功能。此外配备了具有内部访问,充足的存储和驱动器中的可选泊车车库双锁的方式。精明买家投资者,为家庭提供 22 米临街和已被 sub 选项划分 (待布里斯班市议会批准) 这理想的位置已经很容易访问到汽车、 火车、 咖啡馆和餐馆,与网关、 机场和港口的布里斯班一个短的车程。那些寻求备受追捧后贝塞德的生活方式需要那没有比这个杰出的家。业主是致力于其他地方,并会考虑真正的优惠。

看着结果还可以,但是每月超过两万字可能就会收费了。具体的还是要看官网API介绍吧。
原文参考地址: http://www.cnblogs.com/brainy/archive/2012/05/24/2516487.html
有想学习关于嵌入式的大家可以去 www.muxiaofei.com  学习一下,互相交流

你可能感兴趣的:(java)