Home > Java > javaTutorial > body text

Java Baidu Translation API realizes mutual translation between Chinese and English

PHPz
Release: 2023-08-26 23:36:25
Original
842 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template