基于百度API的文本翻译器实现

发布时间 2023-12-26 19:30:38作者: 突破铁皮

软件构造的小实验,现给出源码造福未来学弟

依赖

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.1</version> <!-- 请替换为最新版本 -->
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>
 <!-- https://mvnrepository.com/artifact/com.github.insubstantial/substance -->
<dependency>
     <groupId>com.github.insubstantial</groupId>
     <artifactId>substance</artifactId>
     <version>7.3</version>
</dependency>

翻译功能实现模块

package com.std.www.homework.work1;


import lombok.SneakyThrows;
import okhttp3.*;
import org.json.JSONObject;
import java.io.*;
public class Translation {
    public static final String API_KEY = "hXnhw16cHsb6REP9hKTLX5AU";//替换为你自己的key
    public static final String SECRET_KEY = "kFHPegvFTAlmoNuY2cYSHbSab6QZKmCa";//这个也一样

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @SneakyThrows
    public static String getTranslation(String from,String to,String q){
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"from\":\""+from+"\",\"to\":\""+to+"\",\"q\":\""+q+"\"}");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String res=response.body().string();
//        System.out.println(res);
        return res;
    }


    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }
}

翻译的GUI界面

package com.std.www.homework.work1;

import org.json.JSONArray;
import org.json.JSONObject;
import org.pushingpixels.substance.api.skin.SubstanceGeminiLookAndFeel;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TranslationGUI {
    private static String getType(String s) {
        switch (s) {
            case "中文":
                return "zh";
            case "英语":
                return "en";
            case "法语":
                return "fra";
            case "日语":
                return "jp";
            case "德语":
                return "de";
            case "俄语":
                return "ru";
            case "西班牙语":
                return "spa";
            case "阿拉伯语":
                return "ara";
            default:
                return "en";
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("文本翻译器");
        frame.setSize(600, 380);
        frame.setLayout(new BorderLayout());
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        frame.setBackground(new Color(240, 240, 240));

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridBagLayout());
        mainPanel.setBackground(new Color(255, 255, 255));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        Font font = new Font("Noto", Font.BOLD, 20);

        JTextField formText = new JTextField();
        JTextField toText = new JTextField();
        String[] options = {"中文", "英语", "法语", "日语", "德语",  "俄语", "西班牙语", "阿拉伯语"};
        JComboBox<String> comboBox1 = new JComboBox<>(options);
        JComboBox<String> comboBox2 = new JComboBox<>(options);
        JLabel formLabel = new JLabel("原文");
        JLabel toLabel = new JLabel("译文");


        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(15, 15, 15, 15);
        gbc.fill = GridBagConstraints.BOTH;

        formText.setFont(font);
        formText.setBorder(new TitledBorder(new LineBorder(Color.BLUE), "输入文本"));
        comboBox1.setFont(font);
        formLabel.setFont(new Font("Noto", Font.BOLD, 25));
        toText.setFont(font);
        toText.setBorder(new TitledBorder(new LineBorder(Color.BLUE), "翻译结果"));
        comboBox2.setFont(font);
        toLabel.setFont(new Font("Noto", Font.BOLD, 25));

        JButton translateButton = new JButton("点击翻译");
        translateButton.setFont(font);
        translateButton.setBackground(Color.cyan);
        translateButton.setBorder(new LineBorder(Color.ORANGE));

        translateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object value1 = comboBox1.getSelectedItem();
                Object value2 = comboBox2.getSelectedItem();
                value1 = getType((String) value1);
                value2 = getType((String) value2);
                String q = formText.getText();
                String res = Translation.getTranslation((String) value1, (String) value2, q);
                JSONObject jsonObject = new JSONObject(res);
                JSONObject resultObject = jsonObject.getJSONObject("result");
                JSONArray transResultArray = resultObject.getJSONArray("trans_result");
                JSONObject firstElement = transResultArray.getJSONObject(0);
                String dstValue = firstElement.getString("dst");
                toText.setText(dstValue);
            }
        });

        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(formLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        mainPanel.add(comboBox1, gbc);

        gbc.gridx = 2;
        gbc.gridy = 0;
        mainPanel.add(toLabel, gbc);

        gbc.gridx = 3;
        gbc.gridy = 0;
        mainPanel.add(comboBox2, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        mainPanel.add(formText, gbc);

        gbc.gridx = 2;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        mainPanel.add(toText, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 4;
        mainPanel.add(translateButton, gbc);


        frame.add(mainPanel, BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(new SubstanceGeminiLookAndFeel());
                createAndShowGUI();
            } catch (UnsupportedLookAndFeelException e) {
                e.printStackTrace();
            }
        });
    }
}

运行截图