Use httpclient to achieve free Google translations Api_java

Source: Internet
Author: User
Tags reserved

Because Google Translate API to collect money, so think of a way to steal a machine

1. Send a request to http://translate.google.com with HttpClient

2. Then use Jsoup to parse the HTML and take out the translated text

Copy Code code as follows:

/**
* 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> Translation Tools
* PS: Through 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 is automatically sentenced to the source language system
Protected static final String TAIWAN = "ZH-TW"; In the traditional
Protected static final String of "ZH-CN"; Simple in
Protected static final String 中文版 = "en"; British
Protected static final String JAPAN = "Ja"; Day

 /**
  * <pre>google Translations
  * PS: To Google to automatically judge the source language
  * </PRE>
  *
  * @param text
  * @param target_lang target language
  * @return
  * @throws Exception
  */
 public static string Translate (final string text, final string Target_lang) throws Exception {
  retu RN Translate (text, AUTO, Target_lang);
 }

/**
* <pre>google Translation </pre>
*
* @param text
* @param Src_lang Source language system
* @param target_lang Target Language Department
* @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 translation: Simple--> </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string CN2TW (final String text) throws Exception {
Return translate (text, TAIWAN);
}

/**
* <pre>google translation:--> simplified </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string TW2CN (final String text) throws Exception {
Return translate (text, TAIWAN, the);
}

/**
* <pre>google translation: English--> </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string EN2TW (final String text) throws Exception {
Return translate (text, 中文版, TAIWAN);
}

/**
* <pre>google translation:--> English </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string Tw2en (final String text) throws Exception {
Return translate (text, TAIWAN, 中文版);
}

/**
* <pre>google translation: Japanese--> </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string JP2TW (final String text) throws Exception {
Return translate (text, JAPAN, TAIWAN);
}

/**
* <pre>google translation:--> Day </pre>
*
* @param text
* @return
* @throws Exception
*/
public static string TW2JP (final String text) throws Exception {
Return translate (text, TAIWAN, JAPAN);
}
}

Httpclientutil.java

Copy Code code as follows:

/**
* 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 = 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", 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> download back to 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> save to File</pre> after downloading
*
* @param URL
* @param savefile
* @throws Exception
*/
public static void Download (String URL, File savefile) throws Exception {
Download (URL, savefile, NULL, FALSE);
}

/**
* <pre> Download </pre>
*
* @param URL
* @param savefile
* @param params
* @param isPost
* @return If Savefile==null returns 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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.