通过google进行翻译(java)

通过google的英文翻译进行自动翻译

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * @author Sea Dragon
 * 类说明:利用google进行翻译
 * 2009 2:19:14 PM
 */
public class TranslateUseGoogle {
	public static void main(String[] args) throws  Exception {
		String theword = "my god";    
		String engineUrl = "http://translate.google.com/translate_t";
		String LANGPAIR_EN_CN = "en|zh-CN";
        String urlstr = engineUrl + "?text=" + theword + "&langpair=" + LANGPAIR_EN_CN;   
        HttpClient client = new HttpClient();   
        client.getHostConfiguration().setHost("translate.google.com",80,"http");   
           
          
        PostMethod post = new PostMethod("/translate_t");   
        NameValuePair f01 = new NameValuePair("text",theword);   
        NameValuePair f02 = new NameValuePair("langpair",LANGPAIR_EN_CN);   
        post.setRequestBody(new NameValuePair[]{f01,f02});   
        int scode = client.executeMethod(post);   
        System.out.println(post.getURI());   
        String result = post.getResponseBodyAsString();   
           

        post.releaseConnection();   
//      System.out.println(result);   

//      String result = "
aaa
"; Pattern p = Pattern.compile("
(.*?)
"); Matcher m = p.matcher(result); //System.out.println(m.find()); while(m.find()){ System.out.println(m.group(2)); } } }

 上面用到了common-httpclient.jar这个包

http://www.blogjava.net/Alpha/archive/2007/01/22/95216.html这是一篇关于这个包用法的介绍,挺好的

 

上面还用到了正则表达式,这里有一个很好的网站,很早以前就发现了,但都没把它记下了,这次在重看正则表达式的东西的时候又找到了它,一定要记下来,要不然对不起党和人民啊!

http://www.regexlab.com/zh/

你可能感兴趣的:(技术备忘)