第三十四节(java-实现在线翻译)

NameValue .java文件里:

package com.tanzhou.util;
/**
 * 参数拼接工具类
 * @author Ming
 * @version 1.0
 * 2015-2-7
 */
public class NameValue {
 
    // &client=t&hl=zh-CN&ie=UTF-8&multires=1&oe=UTF-8&otf=1&prev=conf&psl=zh-CN&ptl=zh-CN&sc=1&sl=zh-CN&ssel=3&text=%E4%BD%A0%E5%A5%BD&tl=en&tsel=6
    
    private StringBuilder sb = new StringBuilder();
    
    /**
     * &参数=参数值&参数=参数值 ....
     * @param name 参数
     * @param value 参数值
     */
    public void add(String name,Object value){
        sb.append("&");
        sb.append(name);
        sb.append("=");
        sb.append(value);
    }
    
    public String toString(){
        return sb.toString();
    }
}


///////////////////////////////////////////////////////////////////
Test 文件里:

package com.tanzhou.util;

import org.apache.taglibs.standard.tag.common.xml.IfTag;

public class Test {
   
    public static void main(String[] args){
        String str = Google.translate("晚上好!", "中文简体", "英语");
        
        if(str==null || "".equals(str)){
            System.out.println("失败");
        }else{
            System.out.println("成功!");
            
        //    [[["Good evening !","晚上好!","","Wǎnshàng hǎo!"]],,"zh-CN",,[["Good evening",[3],true,false,1000,0,2,1],["!",[4],false,false,1000,2,3,1]],[["好 晚上",3,[["Good evening",1000,true,false]],[[0,3]],"晚上好!"],["!",4,[["!",1000,false,false]],[[3,4]],""]],,,[["zh-CN"]],3]
            
            String s = Test.mid(str, "[[[", "]]");
            String[] ss = s.split(",");
            
            for(int i=0;i<ss.length;i++){
                System.out.println(ss[i]);
            }
            
        }
    }
    
    /**
     * 截取字符串
     * @param value
     * @param left  [[[
     * @param right  ]]
     * @return
     */
    public static String mid(String value,String left,String right){
        int i = value.indexOf(left) +left.length();
        String str = value.substring(i, value.indexOf(right,i));
        return str;
    }
}


/////////////////////////////////////////////////////////////
WebRequest 文件里:


package com.tanzhou.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 调用接口的核心类
 * @author Ming
 * @version 1.0
 * 2015-2-7
 *
 */
public class WebRequest {

    private static void setRequestHeader(HttpURLConnection conn){
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        conn.setRequestProperty("Accept", "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    }
    
    /**
     * 访问接口的核心方法
     * @param url 接口路径
     * @return 返回的翻译信息
     */
    public static String get(String url){
        
        try {
            URL _url = new URL(url); // 将字符串信息转换成url对象
            // 通过路径打开链接
            HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
            setRequestHeader(conn); // 设置接口的头信息
            // 读取数据
            BufferedReader bis = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line= bis.readLine())!=null){
                sb.append(line);
                sb.append("\n");
            }
            bis.close();
            
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return "";
    }
}


//////////////////////////////////////////////////////////////////
Google .java文件里:

package com.tanzhou.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Encoded;

/**
 * 拼接URL的类
 * @author Ming
 * @version 1.0
 * 2015-2-7
 */
public class Google {

    // http://translate.google.cn/translate_a/t?&client=t&hl=zh-CN&ie=UTF-8&multires=1&oe=UTF-8&otf=1&prev=conf&psl=zh-CN&ptl=zh-CN&sc=1&sl=zh-CN&ssel=3&text=%E4%BD%A0%E5%A5%BD&tl=en&tsel=6
    
    private static final Map<String, String> LANGUAGE = new HashMap<String, String>();
    
    // 静态块
    static{
        LANGUAGE.put("中文简体", "zh_CN");
        LANGUAGE.put("中文繁体", "zh_TW");
        LANGUAGE.put("英语", "en");
        LANGUAGE.put("日语", "ja");
    }
    
    /**
     *  翻译的类(拼接url)
     * @param value 要翻译的内容
     * @param src 要翻译内容的语种
     * @param target  目标语言的语种
     * @return
     */
    public static String translate(String value,String src,String target){
        String url = "http://translate.google.cn/translate_a/t?";
        
        src = LANGUAGE.get(src); // 将语种参数转换成计算机能够识别的编码
        target = LANGUAGE.get(target);
        
        NameValue form = new NameValue();
        form.add("client", "t");
        form.add("hl",src); // 要翻译的语种 src
        form.add("ie", "UTF-8");
        form.add("multires", 1);
        form.add("oe", "UTF-8");
        form.add("otf", 1);
        form.add("prev", "conf");
        form.add("psl", src);  // 要翻译的语种 src
        form.add("ptl", src); // 要翻译的语种 src
        form.add("sc", 1);
        form.add("sl", src);  // 要翻译的语种 src
        form.add("ssel", 3);
        form.add("text", encode(value,"UTF-8"));   // 要翻译的内容
        form.add("tl", target);// 目标语种
        form.add("tsel", 6);
        
        return WebRequest.get(url+form.toString());
    }
    
    public static String encode(String value,String charset){
        try {
            return URLEncoder.encode(value,charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * 截取字符串
     * @param value
     * @param left  [[[
     * @param right  ]]
     * @return
     */
    public static String mid(String value,String left,String right){
        int i = value.indexOf(left) +left.length();
        String str = value.substring(i, value.indexOf(right,i));
        return str;
    }
}



////////////////////////////////////////////////////////////
google.jsp文件里:



<%@ page language="java" import="java.util.*,com.tanzhou.util.*" pageEncoding="GBK"%>
<%@ page contentType="text/html;charset=GBK" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setCharacterEncoding("UTF-8");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'google.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   <%
     String content = (String)request.getAttribute("content");
     String toContent =  (String)request.getAttribute("toContent");
      %>
     <form action="${pageContext.request.contextPath}/check.jsp" method="post">
     <table>
         <tr>
             <td><select id="sel1" name="sel1">
            <option value="中文简体">中文简体</option>
            <option value="英语">英语</option>
            <option value="日语">日语</option>    
            <option value="韩语">韩语</option>
        </select>
        </td>
             <td>
             <select id="sel2" name="sel2">
            <option value="中文简体">中文简体</option>
            <option value="英语">英语</option>
            <option value="日语">日语</option>
            <option value="韩语">韩语</option>
        </select>
             </td>
         </tr>
         <tr>
             <td>
             <textarea name= "content" cols= "40" rows= "5"><%=content==null? "" : content%></textarea>
             </td>
             <td>
             <textarea name= "toContent" cols= "40" rows= "5"><%=toContent==null? "" : toContent%></textarea>
             <input type="submit" value="翻译" />
             </td>
         </tr>
     </table>
         
     </form>
    
  </body>
</html>


///////////////////////////////////////////////////////////////////////
check.jsp文件里:


<%@ page language="java" import="java.util.*,com.tanzhou.util.*" pageEncoding="GBK"%>
<%

    String sel1 = new String(request.getParameter("sel1").getBytes("ISO-8859-1"),"GBK"); // 要翻译的语种
    String sel2 =  new String(request.getParameter("sel2").getBytes("ISO-8859-1"),"GBK"); // 目标语种
    String content =  new String(request.getParameter("content").getBytes("ISO-8859-1"),"GBK"); // 要翻译的内容
    
    String str = Google.translate(content, sel1, sel2);
    System.out.println(str);
    if(str==null || "".equals(str)){
        System.out.println("失败");
    }else{
        System.out.println("成功!");
        
        String s = Google.mid(str, "[[[", "]]");
        String[] ss = s.split(",");
        
        request.setAttribute("content", content);
        // 剔除 引号
        request.setAttribute("toContent", ss[0].substring(1, ss[0].length()-1));
        request.getRequestDispatcher("google.jsp").forward(request, response);
    }

%>


////////////////////////////////////////////////////////////////

index.jsp文件里:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<script type="text/javascript">
  location.href="google.jsp";
</script>

 

posted @ 2015-02-08 10:24  哥的笑百度不到  阅读(540)  评论(0编辑  收藏  举报