最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用httpclient實現(xiàn)免費的google翻譯api

 更新時間:2014年01月24日 14:41:10   作者:  
這篇文章主要介紹了使用httpclient實現(xiàn)免費的google翻譯api的方法,大家參考使用吧

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

1. 用HttpClient發(fā)送一個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 TAIWAN = "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, TAIWAN);
 }

 /**
  * <pre>Google翻譯: 繁中-->簡中</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String tw2cn(final String text) throws Exception {
  return translate(text, TAIWAN, CHINA);
 }

 /**
  * <pre>Google翻譯: 英文-->繁中</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String en2tw(final String text) throws Exception {
  return translate(text, ENGLISH, TAIWAN);
 }

 /**
  * <pre>Google翻譯: 繁中-->英文</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String tw2en(final String text) throws Exception {
  return translate(text, TAIWAN, ENGLISH);
 }

 /**
  * <pre>Google翻譯: 日文-->繁中</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String jp2tw(final String text) throws Exception {
  return translate(text, JAPAN, TAIWAN);
 }

 /**
  * <pre>Google翻譯: 繁中-->日</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String tw2jp(final String text) throws Exception {
  return translate(text, TAIWAN, 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;
 }
}

相關(guān)文章

  • 詳解SpringBoot如何使用Redis和Redis緩存

    詳解SpringBoot如何使用Redis和Redis緩存

    這篇文章主要為大家詳細介紹了SpringBoot如何使用Redis和Redis緩存,文中的示例代碼講解詳細,對我們學習SpringBoot有一定的幫助,需要的可以參考一下
    2022-06-06
  • Java定義隊列結(jié)構(gòu),并實現(xiàn)入隊、出隊操作完整示例

    Java定義隊列結(jié)構(gòu),并實現(xiàn)入隊、出隊操作完整示例

    這篇文章主要介紹了Java定義隊列結(jié)構(gòu),并實現(xiàn)入隊、出隊操作,結(jié)合完整實例形式分析了java數(shù)據(jù)結(jié)構(gòu)中隊列的定義、入隊、出隊、判斷隊列是否為空、打印隊列元素等相關(guān)操作技巧,需要的朋友可以參考下
    2020-02-02
  • 使用Enumeration和Iterator遍歷集合類詳解

    使用Enumeration和Iterator遍歷集合類詳解

    Enumeration和Iterator接口功能相似,而且Iterator的功能還比Enumeration多,那么為什么還要使用Enumeration
    2013-09-09
  • Java多線程中的wait與notify方法詳解

    Java多線程中的wait與notify方法詳解

    這篇文章主要介紹了Java多線程中的wait與notify方法詳解,線程的調(diào)度是無序的,但有些情況要求線程的執(zhí)行是有序的,因此,我們可以使用 wait() 方法來使線程執(zhí)行有序,需要的朋友可以參考下
    2023-08-08
  • Scala小程序詳解及實例代碼

    Scala小程序詳解及實例代碼

    這篇文章主要介紹了Scala 第一個Scala小程序詳解的相關(guān)資料,需要的朋友可以參考下
    2017-01-01
  • 快速了解Spring Boot

    快速了解Spring Boot

    這篇文章主要介紹了快速了解Spring Boot,介紹了其環(huán)境準備,URL中的變量以及模板渲染等內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • Java?使用geotools讀取tiff數(shù)據(jù)的示例代碼

    Java?使用geotools讀取tiff數(shù)據(jù)的示例代碼

    這篇文章主要介紹了Java?通過geotools讀取tiff,一般對于tiff數(shù)據(jù)的讀取,都會借助于gdal,本文結(jié)合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • Java實現(xiàn)天天酷跑小游戲完整代碼(附源碼)

    Java實現(xiàn)天天酷跑小游戲完整代碼(附源碼)

    這篇文章主要介紹了使用Java實現(xiàn)天天酷跑(附源碼),本文通過實例圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12
  • Java之如何讀取Excel獲取真實行數(shù)

    Java之如何讀取Excel獲取真實行數(shù)

    這篇文章主要介紹了Java之如何讀取Excel獲取真實行數(shù)問題,具有很好的參考價值,希望對大家有所幫助。
    2023-06-06
  • Springboot 掃描mapper接口的2種操作

    Springboot 掃描mapper接口的2種操作

    這篇文章主要介紹了Springboot 掃描mapper接口的2種操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01

最新評論

郓城县| 乡宁县| 开鲁县| 延寿县| 胶南市| 广昌县| 方正县| 基隆市| 延川县| 百色市| 亳州市| 喀喇| 姚安县| 璧山县| 瑞安市| 河北省| 尉犁县| 吉水县| 孟村| 平顶山市| 济宁市| 玛曲县| 汝城县| 通辽市| 清远市| 苏州市| 永靖县| 明溪县| 屏山县| 彩票| 连州市| 乐东| 大丰市| 靖西县| 中西区| 黄山市| 县级市| 巴马| 吴桥县| 临海市| 武陟县|