天天看点

[javafx] 多源翻译工具 06.百度翻译

作者:CC挑灯夜读1谷

本节内容:

  • 添加百度翻译
  • 额外内容:程序添加图标

补充:

开发习惯:先完成功能,在功能确定之后,再去优化代码

详情

百度翻译同样需要申请 key

百度翻译开放平台 (baidu.com) 翻译参考文档(有java版demo 代码) :https://fanyi-api.baidu.com/doc/21

为了方便阅读,翻译结果创建 model

package dev.guu.fx.translate.box.baidu;

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class BaiduRoot {
    private String from;
    private String to;

    private BaiduTransResult[] trans_result;
}
           
package dev.guu.fx.translate.box.baidu;


import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class BaiduTransResult {

    private String src;
    private String dst;
}
           

baidu翻译 java 版

package dev.guu.fx.translate.box.baidu;


import dev.guu.kit.string.JsonKit;
import dev.guu.kit.string.StringKit;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.StringJoiner;

@Data
@Accessors(chain = true)
public class BaiduTranslate {
    static String salt = LocalDate.now().toString();
    static String appId = "替换为你的appId";

    static String token = "替换为你的密钥";

    public static void main(String[] args) {
//        System.out.println(translate("我的"));

    }






    public static String translate(String q) {
        String str1 = appId + q + salt + token;
        String sign = md5(str1);

        String url = "https://fanyi-api.baidu.com/api/trans/vip/translate?";
        StringJoiner sj = new StringJoiner("&");
        boolean en = StringKit.isEn(q);
        sj.add("from=" + (en ? "en" : "zh"))
                .add("q=" + q)
                .add("to=" + (en ? "zh" : "en"))
                .add("appid=" + appId)
                .add("salt=" + salt)
                .add("sign=" + sign)
        ;
        url += sj.toString();
        System.out.println(url);
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .POST(HttpRequest.BodyPublishers.ofString("a"))
                .setHeader("Content-type", "application/json")
                .uri(URI.create(url)).build();
        try {
            HttpResponse<String> send = client.send(request, HttpResponse.BodyHandlers.ofString());
            String body = send.body();
            System.out.println(body);
            BaiduRoot baidu = JsonKit.toBean(body, BaiduRoot.class);
            return JsonKit.toJsonFormat(baidu);
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};

    /**
     * 获得一个字符串的MD5值
     *
     * @param input 输入的字符串
     * @return 输入字符串的MD5值
     */
    public static String md5(String input) {
        if (input == null)
            return null;

        try {
            // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数组
            byte[] inputByteArray = input.getBytes(StandardCharsets.UTF_8);
            // inputByteArray是输入字符串转换得到的字节数组
            messageDigest.update(inputByteArray);
            // 转换并返回结果,也是字节数组,包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static String byteArrayToHex(byte[] byteArray) {
        // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }

        // 字符数组组合成字符串返回
        return new String(resultCharArray);

    }

}
           

程序输出区域添加百度翻译相关显示

BoxMain.java

private void createOutput(Pane root) {

        HBox box = new HBox();
        root.getChildren().add(box);
        createYoudao(box);
        createBaidu(box);
    }



    private void createBaidu(HBox parent) {
        Label label = new Label("百度翻译:");
        Button btn = new Button("翻译");

        label.setFont(Font.font("微软雅黑", 24));
        TextArea output = new TextArea();
        output.setPromptText("等待输入...");
        output.setEditable(false);
        output.setFont(Font.font("宋体", 20));
        parent.getChildren().add(new VBox(label,btn, output));
        btn.setOnMouseClicked(e -> {
            String text = inputTextArea.getText();
            if (isBlank(text)) {
                output.setText("请输入");
            } else {
                output.setText("翻译中...");
                // fx的多线程 ,
                Platform.runLater(() -> {
                    String trans = BaiduTranslate.translate(text);
                    output.setText(trans);
                });

            }
        });

    }