前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >神器 | 教你使用 JAVA 开发 类似【百度翻译】功能

神器 | 教你使用 JAVA 开发 类似【百度翻译】功能

作者头像
码神联盟
发布2018-07-31 10:17:13
3660
发布2018-07-31 10:17:13
举报
文章被收录于专栏:码神联盟

需求:使用java来实现一个类似‘百度翻译’的工具

项目下载地址:链接:https://pan.baidu.com/s/1R2hHU7sz7SGbGmCEYDVWYQ 密码:m0o1

技术:java、jdk1.7、百度翻译开发者、SpringBoot、ajax、jsp、js

实现步骤: 1:注册百度翻译开发者平台,开通百度翻译接口API 2:新建如下工程,增加如下代码

项目结构如下:

核心代码

MainServer.java启动类

代码语言:javascript
复制
@SpringBootApplication
@ComponentScan(basePackages={"com.xdl"})//添加的注解
public class MainServer extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(MainServer.class, args);
    }
}

底层类:

代码语言:javascript
复制
@Controller
public class TransController {
    private static final String APP_ID = "你自己百度翻译开发者的ID";
    private static final String SECURITY_KEY = "秘钥";
    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String login() {
        return "index";
    }
    @RequestMapping(value = "/trans", method = RequestMethod.POST)
    public @ResponseBody String trans(Model model, String text) throws Exception {
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String query = text;
        String msg = api.getTransResult(query, "auto", "en");
        model.addAttribute("dst", msg);
        return msg;
    }
    @RequestMapping(value = "/trans2", method = RequestMethod.POST)
    public @ResponseBody String trans2(Model model, String text2) throws Exception {
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String query = text2;
        String msg = api.getTransResult(query, "en", "auto");
        model.addAttribute("dst", msg);
        return msg;
    }
}
代码语言:javascript
复制
public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private String appid;
    private String securityKey;
    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }
    public String getTransResult(String query, String from, String to) throws UnsupportedEncodingException {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }
    private Map<String, String> buildParams(String query, String from, String to) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", appid);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));
        return params;
    }
}
代码语言:javascript
复制
class HttpGet {
    protected static final int SOCKET_TIMEOUT = 10000; // 10S
    protected static final String GET = "GET";
    public static String get(String host, Map<String, String> params) {
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
            String sendUrl = getUrlWithQueryString(host, params);
            // System.out.println("URL:" + sendUrl);
            URL uri = new URL(sendUrl); // 创建URL对象
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }
            conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
            conn.setRequestMethod(GET);
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                System.out.println("Http错误码:" + statusCode);
            }
            // 读取服务器的数据
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            String text = builder.toString();
            close(br); // 关闭数据流
            close(is); // 关闭数据流
            conn.disconnect(); // 断开连接
            return text;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }
        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }
        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }
            if (i != 0) {
                builder.append('&');
            }
            builder.append(key);
            builder.append('=');
            builder.append(encode(value));
            i++;
        }
        return builder.toString();
    }
    protected static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }
        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return input;
    }
    private static TrustManager myX509TrustManager = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };
}

运行结果

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-06-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码神联盟 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档