[javafx] 多源翻譯工具 06.百度翻譯
本節(jié)內(nèi)容:
添加百度翻譯
額外內(nèi)容:程序添加圖標(biāo)
補(bǔ)充:
開發(fā)習(xí)慣:先完成功能,在功能確定之后,再去優(yōu)化代碼
詳情
百度翻譯同樣需要申請 key
百度翻譯開放平臺 (baidu.com) 翻譯參考文檔(有java版demo 代碼)? :https://fanyi-api.baidu.com/doc/21
為了方便閱讀,翻譯結(jié)果創(chuàng)建 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'};
? ?/**
? ? * 獲得一個(gè)字符串的MD5值
? ? *
? ? * @param input 輸入的字符串
? ? * @return 輸入字符串的MD5值
? ? */
? ?public static String md5(String input) {
? ? ? ?if (input == null)
? ? ? ? ? ?return null;
? ? ? ?try {
? ? ? ? ? ?// 拿到一個(gè)MD5轉(zhuǎn)換器(如果想要SHA1參數(shù)換成”SHA1”)
? ? ? ? ? ?MessageDigest messageDigest = MessageDigest.getInstance("MD5");
? ? ? ? ? ?// 輸入的字符串轉(zhuǎn)換成字節(jié)數(shù)組
? ? ? ? ? ?byte[] inputByteArray = input.getBytes(StandardCharsets.UTF_8);
? ? ? ? ? ?// inputByteArray是輸入字符串轉(zhuǎn)換得到的字節(jié)數(shù)組
? ? ? ? ? ?messageDigest.update(inputByteArray);
? ? ? ? ? ?// 轉(zhuǎn)換并返回結(jié)果,也是字節(jié)數(shù)組,包含16個(gè)元素
? ? ? ? ? ?byte[] resultByteArray = messageDigest.digest();
? ? ? ? ? ?// 字符數(shù)組轉(zhuǎn)換成字符串返回
? ? ? ? ? ?return byteArrayToHex(resultByteArray);
? ? ? ?} catch (NoSuchAlgorithmException e) {
? ? ? ? ? ?return null;
? ? ? ?}
? ?}
? ?private static String byteArrayToHex(byte[] byteArray) {
? ? ? ?// new一個(gè)字符數(shù)組,這個(gè)就是用來組成結(jié)果字符串的(解釋一下:一個(gè)byte是八位二進(jìn)制,也就是2位十六進(jìn)制字符(2的8次方等于16的2次方))
? ? ? ?char[] resultCharArray = new char[byteArray.length * 2];
? ? ? ?// 遍歷字節(jié)數(shù)組,通過位運(yùn)算(位運(yùn)算效率高),轉(zhuǎn)換成字符放到字符數(shù)組中去
? ? ? ?int index = 0;
? ? ? ?for (byte b : byteArray) {
? ? ? ? ? ?resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
? ? ? ? ? ?resultCharArray[index++] = hexDigits[b & 0xf];
? ? ? ?}
? ? ? ?// 字符數(shù)組組合成字符串返回
? ? ? ?return new String(resultCharArray);
? ?}
}
程序輸出區(qū)域添加百度翻譯相關(guān)顯示
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);
? ? ? ? ? ? ? ?});
? ? ? ? ? ?}
? ? ? ?});
? ?}
標(biāo)簽: