Home Java javaTutorial Java Baidu Translation API realizes mutual translation between Chinese and English

Java Baidu Translation API realizes mutual translation between Chinese and English

Aug 26, 2023 pm 11:36 PM
English translation Baidu API java implementation translation

Java Baidu Translation API realizes mutual translation between Chinese and English

Java Baidu Translation API realizes mutual translation between Chinese and English

In recent years, with the increasing demand for mutual translation between Chinese and English, various translation tools and APIs have also emerged. born. Among them, Baidu Translation API is one of the tools commonly used by many developers. This article will introduce how to use Java language combined with Baidu Translation API to realize the function of mutual translation between Chinese and English.

First, we need to register a Baidu developer account and create a translation application. When creating a translation application, we will obtain an AppID and a key (App Key). This information is the necessary credentials for us to call Baidu Translation API.

Next, we need to introduce relevant dependencies. In the project's pom.xml file, add the following code:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>
Copy after login

The above two dependencies are the Apache HttpClient and JSON libraries, which are used to send HTTP requests and process JSON data.

Next, we need to create a translation class to encapsulate the method of calling Baidu Translation API. In this class, we need to define a method that accepts the text to be translated and the target language as parameters and returns the translation result. The following is a sample code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONObject;

public class Translation {
    private final String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private String appId = "your_app_id";
    private String appKey = "your_app_key";
    
    public String translate(String text, String targetLang) {
        try {
            String encodedText = URLEncoder.encode(text, "UTF-8");
            String fullUrl = url + "?q=" + encodedText + "&from=auto&to=" + targetLang + "&appid=" + appId + "&salt=1&sign=" + generateSign(text);

            URL apiUrl = new URL(fullUrl);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            JSONObject jsonResponse = new JSONObject(response.toString());
            JSONArray transResult = jsonResponse.getJSONArray("trans_result");
            JSONObject result = transResult.getJSONObject(0);

            String translatedText = result.getString("dst");
            return translatedText;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    
    private String generateSign(String text) {
        // 在这里根据百度翻译API的要求,生成签名
        // 可以参考百度翻译API的文档
        return "";
    }
}
Copy after login

In the above code, we use Apache HttpClient to send HTTP requests and parse the returned JSON data through the JSON library. We need to replace "your_app_id" and "your_app_key" in the code with our actual AppID and key.

Finally, we can call the translation class method in the main class of the project to realize the function of translating between Chinese and English. The following is a sample code:

public class Main {
    public static void main(String[] args) {
        Translation translation = new Translation();
        
        // 中文翻译为英文
        String text = "你好,世界!";
        String targetLang = "en";
        String translatedText = translation.translate(text, targetLang);
        System.out.println("中文翻译为英文: " + translatedText);
        
        // 英文翻译为中文
        String textToTranslate = "Hello, world!";
        String targetLanguage = "zh";
        String translatedText = translation.translate(textToTranslate, targetLanguage);
        System.out.println("英文翻译为中文: " + translatedText);
    }
}
Copy after login

By running the above code, we can achieve a simple mutual translation function between Chinese and English.

To summarize, this article introduces how to use Java language combined with Baidu Translation API to realize the function of mutual translation between Chinese and English. By using the Baidu Translation API, we can easily implement the text translation function and use it flexibly in development. I hope that the sample code in this article can provide some reference for readers to apply Baidu Translation API in actual projects.

The above is the detailed content of Java Baidu Translation API realizes mutual translation between Chinese and English. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles