Home > Java > javaTutorial > body text

Utilize the Java Baidu Translation API to achieve accurate and natural translation between multiple languages

PHPz
Release: 2023-08-05 20:51:20
Original
1178 people have browsed it

Use Java Baidu Translation API to achieve accurate and natural translation between multiple languages

In today's era of globalization, language communication has become more and more important. Sometimes we need to translate one language into another language to achieve the purpose of information transmission. In practical applications, we hope that translation tools can accurately and naturally translate languages ​​so that information can be expressed more fluently. Fortunately, Baidu provides a powerful translation API that allows us to use Java language to achieve accurate and natural language translation.

First of all, we need to apply for the key of Baidu Translation API. Go to Baidu Translation Open Platform (http://api.fanyi.baidu.com/api/trans/product/index) to register a developer account and create a new application.

Next we need to import the relevant Java libraries. Add the following dependencies in the project's pom.xml file:

<dependencies>
    <dependency>
        <groupId>com.github.openjson</groupId>
        <artifactId>org.json</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.3</version>
    </dependency>
</dependencies>
Copy after login

Then create a Java class named BaiduTranslator to handle the translation logic. The code is as follows:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URLEncoder;

public class BaiduTranslator {
    private static final String API_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static final String APP_ID = "your_app_id";
    private static final String SECRET_KEY = "your_secret_key";

    public static String translate(String query, String from, String to) throws Exception {
        String salt = String.valueOf(System.currentTimeMillis());

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(API_URL);

        String sign = MD5Util.md5(APP_ID + query + salt + SECRET_KEY);

        StringBuilder params = new StringBuilder();
        params.append("q=").append(URLEncoder.encode(query, "UTF-8"));
        params.append("&from=").append(from);
        params.append("&to=").append(to);
        params.append("&appid=").append(APP_ID);
        params.append("&salt=").append(salt);
        params.append("&sign=").append(sign);

        StringEntity entity = new StringEntity(params.toString(), "UTF-8");
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity httpEntity = response.getEntity();

        String resultJson = EntityUtils.toString(httpEntity, "UTF-8");

        JSONObject jsonObject = new JSONObject(resultJson);
        JSONArray transArray = jsonObject.getJSONArray("trans_result");
        JSONObject transObj = transArray.getJSONObject(0);

        return transObj.getString("dst");
    }
}
Copy after login

In the above code, we use the Apache HttpClient library to send HTTP requests to call Baidu Translation API. At the same time, we also used the org.json library to parse the returned JSON data.

In the API_URL, APP_ID and SECRET_KEY variables, we need to replace them with our own application information. This information can be found in the application management of Baidu Translation Open Platform.

Finally, we can call the BaiduTranslator class in the main class for translation. For example, we can write a TranslateApp class:

public class TranslateApp {
    public static void main(String[] args) {
        try {
            String query = "Hello, world!";
            String from = "en";
            String to = "zh";

            String translation = BaiduTranslator.translate(query, from, to);

            System.out.println("翻译结果:" + translation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

In this example, we translate the English string "Hello, world!" into Chinese. You can also call the BaiduTranslator class to implement translation in other languages ​​according to your own needs.

Using the Java Baidu Translation API, we can achieve accurate and natural translation between multiple languages ​​to meet the language communication needs in the era of globalization. This powerful tool can be used in various application scenarios, such as online translation tools, multi-language websites, multinational enterprises, etc.

I hope this article can help readers understand how to use the Java Baidu Translation API to achieve accurate and natural translation between multiple languages ​​to improve the efficiency and accuracy of language communication.

The above is the detailed content of Utilize the Java Baidu Translation API to achieve accurate and natural translation between multiple languages. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!