1. 程式人生 > >Java 呼叫 有道翻譯API

Java 呼叫 有道翻譯API


利用有道API進行翻譯
   
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);
 }

}