欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用httpclient实现免费的google翻译api

程序员文章站 2024-02-20 12:29:46
由於google translate api要收錢 ,因此想了一個偷機的方法 1. 用httpclient發送一個request給http://translate.go...

由於google translate api要收錢 ,因此想了一個偷機的方法

1. 用httpclient發送一個request給http://translate.google.com

2. 再用jsoup來parse html, 並取出翻譯後的文字

复制代码 代码如下:

/**
 * copyright (c) blackbear, inc all rights reserved.
 */
package org.bb.util.i18n;

import java.io.inputstream;
import java.net.urlencoder;
import java.text.messageformat;

import org.apache.commons.io.ioutils;

import org.bb.util.net.http.httpclientutil;
import org.jsoup.jsoup;
import org.jsoup.nodes.document;
import org.jsoup.nodes.element;

/**
 * translateutil
 *
 * <pre>翻譯工具
 * ps: 透過google translate
 * </pre>
 *
 * @author catty
 * @version 1.0, created on 2011/9/2
 */
public class translateutil {

 protected static final string url_template = "http://translate.google.com/?langpair={0}&text={1}";
 protected static final string id_resultbox = "result_box";
 protected static final string encoding = "utf-8";

 protected static final string auto = "auto"; // google自動判斷來源語系
 protected static final string * = "zh-tw"; // 繁中
 protected static final string china = "zh-cn"; // 簡中
 protected static final string english = "en"; // 英
 protected static final string japan = "ja"; // 日

 /**
  * <pre>google翻譯
  * ps: 交由google自動判斷來源語系
  * </pre>
  *
  * @param text
  * @param target_lang 目標語系
  * @return
  * @throws exception
  */
 public static string translate(final string text, final string target_lang) throws exception {
  return translate(text, auto, target_lang);
 }

 /**
  * <pre>google翻譯</pre>
  *
  * @param text
  * @param src_lang 來源語系
  * @param target_lang 目標語系
  * @return
  * @throws exception
  */
 public static string translate(final string text, final string src_lang, final string target_lang)
   throws exception {
  inputstream is = null;
  document doc = null;
  element ele = null;
  try {
   // create url string
   string url = messageformat.format(url_template,
     urlencoder.encode(src_lang + "|" + target_lang, encoding),
     urlencoder.encode(text, encoding));

   // connect & download html
   is = httpclientutil.downloadasstream(url);

   // parse html by jsoup
   doc = jsoup.parse(is, encoding, "");
   ele = doc.getelementbyid(id_resultbox);
   string result = ele.text();
   return result;

  } finally {
   ioutils.closequietly(is);
   is = null;
   doc = null;
   ele = null;
  }
 }

 /**
  * <pre>google翻譯: 簡中-->繁中</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string cn2tw(final string text) throws exception {
  return translate(text, china, *);
 }

 /**
  * <pre>google翻譯: 繁中-->簡中</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string tw2cn(final string text) throws exception {
  return translate(text, *, china);
 }

 /**
  * <pre>google翻譯: 英文-->繁中</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string en2tw(final string text) throws exception {
  return translate(text, english, *);
 }

 /**
  * <pre>google翻譯: 繁中-->英文</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string tw2en(final string text) throws exception {
  return translate(text, *, english);
 }

 /**
  * <pre>google翻譯: 日文-->繁中</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string jp2tw(final string text) throws exception {
  return translate(text, japan, *);
 }

 /**
  * <pre>google翻譯: 繁中-->日</pre>
  *
  * @param text
  * @return
  * @throws exception
  */
 public static string tw2jp(final string text) throws exception {
  return translate(text, *, japan);
 }
}

httpclientutil.java

复制代码 代码如下:

/**
 * copyright (c) blackbear, inc all rights reserved.
 */
package org.bb.util.net.http;

import java.io.bufferedinputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.io.inputstream;
import java.util.map;

import org.apache.commons.io.ioutils;
import org.apache.commons.logging.log;
import org.apache.commons.logging.logfactory;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.methods.httprequestbase;
import org.apache.http.conn.scheme.plainsocketfactory;
import org.apache.http.conn.scheme.scheme;
import org.apache.http.conn.scheme.schemeregistry;
import org.apache.http.conn.ssl.sslsocketfactory;
import org.apache.http.entity.bufferedhttpentity;
import org.apache.http.impl.client.defaulthttpclient;
import org.apache.http.impl.conn.tsccm.threadsafeclientconnmanager;
import org.apache.http.params.basichttpparams;

/**
 * postutil.java
 *
 * @author catty
 * @version 1.0, created on 2008/2/20
 */
public class httpclientutil {

 protected static log log = logfactory.getlog(httpclientutil.class);
 protected static httpclient httpclient = null;
 protected static int maxtotal = 200;
 protected static int maxperroute = 20;
 protected static string useragent = "mozilla/5.0 (windows nt 6.1; wow64) applewebkit/535.7 (khtml, like gecko) chrome/16.0.912.77 safari/535.7";

 static {
  if (httpclient == null) {
   // ~~~~~~~~~~~~~~~~~~~~
   // create httpclient
   // ~~~~~~~~~~~~~~~~~~~~
   schemeregistry reg = new schemeregistry();
   reg.register(new scheme("http", 80, plainsocketfactory.getsocketfactory()));
   reg.register(new scheme("https", 443, sslsocketfactory.getsocketfactory()));
   threadsafeclientconnmanager cm = new threadsafeclientconnmanager(reg);
   cm.setmaxtotal(maxtotal);
   cm.setdefaultmaxperroute(maxperroute);
   httpclient = new defaulthttpclient(cm);
  }
 }

 /**
  * <pre>下載後回傳inputstream</pre>
  *
  * @param url
  * @return
  * @throws exception
  */
 public static inputstream downloadasstream(string url) throws exception {
  inputstream is = (inputstream) download(url, null, null, false);
  return is;
 }

 /**
  * <pre>下載後儲存到file</pre>
  *
  * @param url
  * @param savefile
  * @throws exception
  */
 public static void download(string url, file savefile) throws exception {
  download(url, savefile, null, false);
 }

 /**
  * <pre>下載</pre>
  *
  * @param url
  * @param savefile
  * @param params
  * @param ispost
  * @return 如果savefile==null則回傳inputstream, 否則回傳savefile
  * @throws exception
  */
 public static object download(final string url, final file savefile, final map<string, string> params,
   final boolean ispost) throws exception {

  boolean savetofile = savefile != null;

  // check dir exist ??
  if (savetofile && savefile.getparentfile().exists() == false) {
   savefile.getparentfile().mkdirs();
  }

  exception err = null;
  httprequestbase request = null;
  httpresponse response = null;
  httpentity entity = null;
  fileoutputstream fos = null;
  object result = null;

  try {
   // create request
   if (ispost) {
    request = new httppost(url);
   } else {
    request = new httpget(url);
   }

   // add header & params
   addheaderandparams(request, params);

   // connect
   response = httpclient.execute(request);
   entity = response.getentity();
   entity = new bufferedhttpentity(entity);

   // get result
   if (savetofile) {// save to disk
    fos = new fileoutputstream(savefile);
    ioutils.copy(entity.getcontent(), fos);
    result = savefile;
   } else { // warp to inpustream
    result = new bufferedinputstream(entity.getcontent());
   }

  } catch (exception e) {
   err = e;
  } finally {

   // close
   ioutils.closequietly(fos);

   // clear
   request = null;
   response = null;
   entity = null;

   if (err != null) {
    throw err;
   }

   return result;
  }

 }

 protected static void addheaderandparams(final httprequestbase request, final map<string, string> params) {
  // add default header
  request.addheader("user-agent", useragent);

  // add params
  if (params != null) {

   // map --> httpparams
   basichttpparams myparams = new basichttpparams();
   for (string key : params.keyset()) {
    myparams.setparameter(key, params.get(key));
   }

   request.setparams(myparams);
  }
 }

 public static httpclient gethttpclient() {
  return httpclient;
 }

 public static void sethttpclient(httpclient httpclient) {
  httpclientutil.httpclient = httpclient;
 }

 public static int getmaxtotal() {
  return maxtotal;
 }

 public static void setmaxtotal(int maxtotal) {
  httpclientutil.maxtotal = maxtotal;
 }

 public static int getmaxperroute() {
  return maxperroute;
 }

 public static void setmaxperroute(int maxperroute) {
  httpclientutil.maxperroute = maxperroute;
 }

 public static string getuseragent() {
  return useragent;
 }

 public static void setuseragent(string useragent) {
  httpclientutil.useragent = useragent;
 }
}