首页 > 其他分享 >调用百度的接口,实现多种语言的翻译

调用百度的接口,实现多种语言的翻译

时间:2024-11-12 14:19:03浏览次数:1  
标签:return String 多种语言 接口 char static new public 百度

先把工具类下载下来,直接拖进去:

/**
 * Base64 工具类
 */
public class Base64Util {
    private static final char last2byte = (char) Integer.parseInt("00000011", 2);
    private static final char last4byte = (char) Integer.parseInt("00001111", 2);
    private static final char last6byte = (char) Integer.parseInt("00111111", 2);
    private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
    private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
    private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    public Base64Util() {
    }

    public static String encode(byte[] from) {
        StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3);
        int num = 0;
        char currentByte = 0;

        int i;
        for (i = 0; i < from.length; ++i) {
            for (num %= 8; num < 8; num += 6) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                    case 1:
                    case 3:
                    case 5:
                    default:
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6);
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if (i + 1 < from.length) {
                            currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4);
                        }
                }

                to.append(encodeTable[currentByte]);
            }
        }

        if (to.length() % 4 != 0) {
            for (i = 4 - to.length() % 4; i > 0; --i) {
                to.append("=");
            }
        }

        return to.toString();
    }
}
import java.io.*;

/**
 * 文件读取工具类
 */
public class FileUtil {

    /**
     * 读取文件内容,作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } 

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        } 

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流  
        FileInputStream fis = new FileInputStream(filePath);  
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];  
        // 用于保存实际读取的字节数  
        int hasRead = 0;  
        while ( (hasRead = fis.read(bbuf)) > 0 ) {  
            sb.append(new String(bbuf, 0, hasRead));  
        }  
        fis.close();  
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }
}
/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}

然后是具体的实现:

import okhttp3.*;
import org.json.JSONObject;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.io.IOException;

public class TranslatorApp extends JFrame {

    public static final String API_KEY = "123456";  // 替换为你的 API_KEY
    public static final String SECRET_KEY = "123456";  // 替换为你的 SECRET_KEY

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

    private JTextArea inputTextArea;
    private JTextArea resultTextArea;
    private JComboBox<String> languageComboBox;
    private JLabel statusLabel;

    public TranslatorApp() {
        setTitle("多语言翻译器");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 设置整体背景色和边距
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(new Color(240, 240, 240));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        setContentPane(mainPanel);

        // 顶部面板
        JPanel topPanel = new JPanel(new BorderLayout(10, 10));
        topPanel.setOpaque(false);

        // 输入区域
        JPanel inputPanel = new JPanel(new BorderLayout(5, 5));
        inputPanel.setOpaque(false);
        JLabel inputLabel = new JLabel("输入文本:");
        inputLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        inputTextArea = new JTextArea(5, 30);
        inputTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        inputTextArea.setLineWrap(true);
        inputTextArea.setWrapStyleWord(true);
        JScrollPane inputScrollPane = new JScrollPane(inputTextArea);
        inputScrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));

        inputPanel.add(inputLabel, BorderLayout.NORTH);
        inputPanel.add(inputScrollPane, BorderLayout.CENTER);

        // 语言选择和翻译按钮面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        controlPanel.setOpaque(false);

        String[] languages = new String[]{
                "中译英 (English)",
                "中译日 (日本語)",
                "中译俄 (Русский)",
                "中译法 (Français)",
                "英译中 (中文)"
        };

        languageComboBox = new JComboBox<>(languages);
        languageComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        languageComboBox.setPreferredSize(new Dimension(150, 30));

        JButton translateButton = createStyledButton("开始翻译");

        controlPanel.add(new JLabel("目标语言:"));
        controlPanel.add(languageComboBox);
        controlPanel.add(translateButton);

        // 结果显示区域
        JPanel resultPanel = new JPanel(new BorderLayout(5, 5));
        resultPanel.setOpaque(false);
        JLabel resultLabel = new JLabel("翻译结果:");
        resultLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        resultTextArea = new JTextArea(5, 30);
        resultTextArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        resultTextArea.setLineWrap(true);
        resultTextArea.setWrapStyleWord(true);
        resultTextArea.setEditable(false);
        resultTextArea.setBackground(new Color(250, 250, 250));
        JScrollPane resultScrollPane = new JScrollPane(resultTextArea);
        resultScrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));

        resultPanel.add(resultLabel, BorderLayout.NORTH);
        resultPanel.add(resultScrollPane, BorderLayout.CENTER);

        // 状态栏
        statusLabel = new JLabel("就绪");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        statusLabel.setForeground(Color.GRAY);

        // 组装界面
        topPanel.add(inputPanel, BorderLayout.CENTER);
        topPanel.add(controlPanel, BorderLayout.SOUTH);

        mainPanel.add(topPanel, BorderLayout.NORTH);
        mainPanel.add(resultPanel, BorderLayout.CENTER);
        mainPanel.add(statusLabel, BorderLayout.SOUTH);

        // 设置翻译按钮事件
        translateButton.addActionListener(e -> performTranslation());
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setPreferredSize(new Dimension(100, 30));
        button.setBackground(new Color(66, 139, 202));
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        return button;
    }

    private void performTranslation() {
        String textToTranslate = inputTextArea.getText().trim();

        if (textToTranslate.isEmpty()) {
            showError("请输入要翻译的文本");
            return;
        }

        // 设置语言代码
        String[] languagePair = getLanguagePair();
        String fromLanguage = languagePair[0];
        String toLanguage = languagePair[1];

        // 开始翻译
        statusLabel.setText("正在翻译...");
        resultTextArea.setText("");

        // 使用SwingWorker在后台执行翻译
        new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws Exception {
                return translateText(fromLanguage, toLanguage, textToTranslate);
            }

            @Override
            protected void done() {
                try {
                    String result = get();
                    resultTextArea.setText(result);
                    statusLabel.setText("翻译完成");
                } catch (Exception e) {
                    showError("翻译失败: " + e.getMessage());
                }
            }
        }.execute();
    }

    private String[] getLanguagePair() {
        String selection = (String) languageComboBox.getSelectedItem();
        switch (selection) {
            case "中译英 (English)": return new String[]{"zh", "en"};
            case "中译日 (日本語)": return new String[]{"zh", "jp"};
            case "中译俄 (Русский)": return new String[]{"zh", "ru"};
            case "中译法 (Français)": return new String[]{"zh", "fra"};
            case "英译中 (中文)": return new String[]{"en", "zh"};
            default: return new String[]{"zh", "en"};
        }
    }

    private void showError(String message) {
        statusLabel.setText("错误: " + message);
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    // 翻译方法保持不变,但增加错误处理
    public static String translateText(String from, String to, String q) throws IOException {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType,
                    new JSONObject().put("from", from).put("to", to).put("q", q).toString());

            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();

            Response response = HTTP_CLIENT.newCall(request).execute();

            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseBody);
                return jsonResponse.getJSONObject("result").getJSONArray("trans_result").getJSONObject(0).getString("dst");
            } else {
                throw new IOException("翻译请求失败,状态码:" + response.code());
            }
        } catch (Exception e) {
            throw new IOException("翻译过程中发生错误: " + e.getMessage());
        }
    }

    // getAccessToken方法保持不变
    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")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();

        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            return new JSONObject(responseBody).getString("access_token");
        } else {
            throw new IOException("获取Access Token失败,状态码:" + response.code());
        }
    }

    public static void main(String[] args) {
        try {
            // 设置界面风格为系统默认外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(() -> {
            TranslatorApp app = new TranslatorApp();
            app.setVisible(true);
        });
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SoftWareConstruction</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>22</maven.compiler.source>
        <maven.compiler.target>22</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20210307</version>
        </dependency>


        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.12.0</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
    </dependencies>

</project>

把pom也给一下吧

标签:return,String,多种语言,接口,char,static,new,public,百度
From: https://www.cnblogs.com/muzhaodi/p/18541814

相关文章

  • 根据拼多多商品链接获取拼多多商品详情接口(pinduoduo.item_get_app)
    以下是使用拼多多商品详情接口 pinduoduo.item_get_app 的一般步骤:接口调用前的准备工作:注册并登录拼多多开放平台:首先需要在拼多多开放平台官网上注册一个账号,并完成登录。创建应用并获取API密钥:在开放平台中创建一个新的应用,以获取该应用的 appkey(即调用 key)和 a......
  • 拼多多商品详情接口(Pdd.item_get)
    拼多多商品详情接口(Pdd.item_get)是拼多多开放平台提供的用于获取商品详细信息的API接口23。以下是关于该接口的详细介绍:申请与准备:注册账号:首先需要在拼多多开放平台上注册一个账号。创建应用并获取API密钥:在开发者后台创建一个应用,以获取相应的API密钥。此密钥将用......
  • 高级语言调用C接口(一)基础类型与基础类型指针的对应关系
    基础类型C变量类型Java变量类型C#变量类型python变量类型arkts变量类型备注intintintc_intnumberunsignedintlonguintc_uintnumbershortshortshortc_shortnumberunsignedshortintushortc_ushortnumberlongintintc_longnumber32位系统中,C中的long型占4字节,可以当作in......
  • Jmeter接口测试流程详解
    1.Jmeter介绍Jmeter是一个基于java的开源性能测试工具,支持多线程并发测试。安装需先安装JDK,然后下载Jmeter并配置环境变量。主要元件包括测试计划、线程组、配置元件、取样器、断言和监听器等,它们按照特定顺序执行。线程组定义用户数和请求间隔,取样器发送不同类型的请求,断言......
  • 接口3
    当然可以,编写单元测试可以帮助验证IpAddressService接口的实现是否按预期工作。我们将使用JUnit和Mockito来编写单元测试。以下是一个示例单元测试类:单元测试类packagecom.example.service.impl;importcom.example.entity.AllIpAddressCheckRequest;importcom.examp......
  • D64【python 接口自动化学习】- python基础之数据库
    day64SQL-DQL-基础查询学习日期:20241110学习目标:MySQL数据库--133SQL-DQL-基础查询学习笔记:基础数据查询基础数据查询-过滤总结基础查询的语法:select字段列表|*from表过滤查询的语法:select字段列表|*from表where条件判断......
  • D65【python 接口自动化学习】- python基础之数据库
    day65SQL-DQL-分组聚合学习日期:20241111学习目标:MySQL数据库--133SQL-DQL-分组聚合学习笔记:分组聚合总结分组聚合的语法分组聚合的注意事项groupby中出现了哪个列,哪个列才能出现在select中的非聚合中......
  • 接口1源代码分析
    当然可以,下面是对addDepartmentPermission方法的详细解释,包括每一行代码的功能和作用:方法签名@Override@Transactional(rollbackFor=Exception.class)publicAddDepartmentPermissionResponseaddDepartmentPermission(AddDepartmentPermissionRequestrequest){@Over......
  • 接口1
    importstaticorg.mockito.Mockito.;importstaticorg.junit.jupiter.api.Assertions.;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.extension.ExtendWith;importorg.mockito.InjectMocks;importorg.......
  • RL 基础 | 如何使用 OpenAI Gym 接口,搭建自定义 RL 环境(详细版)
    参考:官方链接:Gymdocumentation|Makeyourowncustomenvironment腾讯云|OpenAIGym中级教程——环境定制与创建知乎|如何在Gym中注册自定义环境?g,写完了才发现自己曾经写过一篇:RL基础|如何搭建自定义gym环境(这篇博客适用于gym的接口,gymnasium接口也差不......