亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用httpclient實(shí)現(xiàn)免費(fèi)的google翻譯api

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

由於Google translate API要收錢 ,因此想了一個(gè)偷機(jī)的方法

1. 用HttpClient發(fā)送一個(gè)request給http://translate.google.com

2. 再用Jsoup來(lái)parse html, 並取出翻譯後的文字

復(fù)制代碼 代碼如下:

/**
 * 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: 透過(guò)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自動(dòng)判斷來(lái)源語(yǔ)系
 protected static final String TAIWAN = "zh-TW"; // 繁中
 protected static final String CHINA = "zh-CN"; // 簡(jiǎn)中
 protected static final String ENGLISH = "en"; // 英
 protected static final String JAPAN = "ja"; // 日

 /**
  * <pre>Google翻譯
  * PS: 交由google自動(dòng)判斷來(lái)源語(yǔ)系
  * </pre>
  *
  * @param text
  * @param target_lang 目標(biāo)語(yǔ)系
  * @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 來(lái)源語(yǔ)系
  * @param target_lang 目標(biāo)語(yǔ)系
  * @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翻譯: 簡(jiǎn)中-->繁中</pre>
  *
  * @param text
  * @return
  * @throws Exception
  */
 public static String cn2tw(final String text) throws Exception {
  return translate(text, CHINA, TAIWAN);
 }

 /**
  * <pre>Google翻譯: 繁中-->簡(jiǎn)中</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

復(fù)制代碼 代碼如下:

/**
 * 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>下載後儲(chǔ)存到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)文章

  • IntelliJ IDEA Tomcat控制臺(tái)中文亂碼問(wèn)題的四種解決方案

    IntelliJ IDEA Tomcat控制臺(tái)中文亂碼問(wèn)題的四種解決方案

    這篇文章主要給大家分享了4種方法完美解決IntelliJ IDEA Tomcat控制臺(tái)中文亂碼問(wèn)題,文中有詳細(xì)的圖文介紹,對(duì)我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2023-08-08
  • 深入了解Spring的Bean生命周期

    深入了解Spring的Bean生命周期

    這篇文章主要為大家介紹了Spring的Bean生命周期,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定的參考價(jià)值,感興趣的可以學(xué)習(xí)一下
    2022-01-01
  • 如何安裝jdk及安裝MyEclipse的圖文教程

    如何安裝jdk及安裝MyEclipse的圖文教程

    這篇文章主要介紹了如何安裝jdk及安裝MyEclipse的圖文教程,需要的朋友可以參考下
    2018-03-03
  • 詳解java動(dòng)態(tài)代理的2種實(shí)現(xiàn)方式

    詳解java動(dòng)態(tài)代理的2種實(shí)現(xiàn)方式

    目前Java開發(fā)包中包含了對(duì)動(dòng)態(tài)代理的支持,但是其實(shí)現(xiàn)只支持對(duì)接口的的實(shí)現(xiàn)。這篇文章主要介紹了詳解java動(dòng)態(tài)代理的2種實(shí)現(xiàn)方式 ,有興趣的可以了解一下。
    2016-11-11
  • Spring XML Schema擴(kuò)展機(jī)制的使用示例

    Spring XML Schema擴(kuò)展機(jī)制的使用示例

    所謂整合,即在Spring的框架下進(jìn)行擴(kuò)展,讓框架能無(wú)縫的與Spring工程配合使用。Spring設(shè)計(jì)了良好的擴(kuò)展的機(jī)制,本文將對(duì)Spring的擴(kuò)展方法及原理進(jìn)行簡(jiǎn)單介紹。
    2021-05-05
  • Java 圖文并茂講解主方法中的String[] args參數(shù)作用

    Java 圖文并茂講解主方法中的String[] args參數(shù)作用

    很多老鐵不清楚JAVA主方法中main()里面的的參數(shù)是什么意思,以及有什么作用,接下來(lái)給大家用最通俗易懂的話來(lái)講解,還不清楚的朋友來(lái)看看吧
    2022-04-04
  • 淺析 ArrayList 和 LinkedList 有什么區(qū)別

    淺析 ArrayList 和 LinkedList 有什么區(qū)別

    ArrayList 和 LinkedList 有什么區(qū)別,是面試官非常喜歡問(wèn)的一個(gè)問(wèn)題。今天通過(guò)本文給大家詳細(xì)介紹下,感興趣的朋友跟隨小編一起看看吧
    2020-10-10
  • Java讀文件修改默認(rèn)換行符的實(shí)現(xiàn)

    Java讀文件修改默認(rèn)換行符的實(shí)現(xiàn)

    這篇文章主要介紹了Java讀文件修改默認(rèn)換行符的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Spring?Boot?打包成Jar包運(yùn)行原理分析

    Spring?Boot?打包成Jar包運(yùn)行原理分析

    這篇文章主要為大家介紹了Spring?Boot?打包成Jar包運(yùn)行的原理分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • 5個(gè)步驟讓你明白多線程和線程安全

    5個(gè)步驟讓你明白多線程和線程安全

    本文詳細(xì)講解了多線程和線程安全的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12

最新評(píng)論