Home > Java > javaTutorial > body text

Implementation of Java Baidu Translation API for Chinese and Spanish translation

PHPz
Release: 2023-08-08 14:10:42
Original
859 people have browsed it

Implementation of Java Baidu Translation API for Chinese and Spanish translation

Java Baidu translation API implementation for mutual translation between Chinese and Spanish

Introduction:
With the deepening development of globalization, the communication and communication between different languages The need for translation is increasing. This article will introduce how to use Java to develop a simple program and use Baidu Translation API to achieve mutual translation between Chinese and Spanish.

  1. Get the Access Token of Baidu Translation API
    First, we need to obtain the Access Token of Baidu Translation API. Access Token is the necessary credential for calling API. We can obtain Access Token by visiting Baidu Developer Platform (https://fanyi-api.baidu.com/). After successfully registering and logging in, create a new application and obtain the Access Token in the application. Remember, Access Token has a certain validity period and needs to be renewed regularly.
  2. Import the necessary Java packages
    We need to import the necessary Java packages to achieve communication with Baidu Translation API. In our program, we will use the Apache HttpClient library to send HTTP requests and the JSON library to parse the returned JSON data. It will be more convenient to use Maven to manage dependencies.

Add the following dependencies in the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.10</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180813</version>
    </dependency>
</dependencies>
Copy after login
  1. Implement the Chinese to Spanish translation function
    The following is a sample code that implements Function to translate Chinese text into Spanish:
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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class TranslationClient {

    private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    private static final String ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
    private static final String FROM = "zh";
    private static final String TO = "es";

    public static void main(String[] args) {
        String text = "你好世界";

        try {
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            String body = String.format("q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s",
                    text, FROM, TO, APP_ID, salt, sign);

            httpPost.setEntity(new StringEntity(body));

            HttpResponse response = httpClient.execute(httpPost);         
            HttpEntity entity = response.getEntity();
            String responseJson = EntityUtils.toString(entity);

            JSONObject jsonObject = new JSONObject(responseJson);
            String translation = jsonObject.getJSONArray("trans_result").getJSONObject(0).getString("dst");

            System.out.println("Translation: " + translation);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

Please note that YOUR_ACCESS_TOKEN in the above code should be replaced with your own Access Token. Among them, API_URL is the request address of Baidu Translation API; FROM and TO represent the source language and target language respectively; text is the text to be translated.

  1. Implementing the translation function from Spanish to Chinese
    To realize the translation function from Spanish to Chinese, we only need to set FROM and TO to "es" and "zh" respectively, and Just pass the Spanish text to be translated to the API. The sample 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.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class TranslationClient {

    private static final String API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    private static final String ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
    private static final String FROM = "es";
    private static final String TO = "zh";

    public static void main(String[] args) {
        String text = "Hola mundo";

        try {
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            String body = String.format("q=%s&from=%s&to=%s&appid=%s&salt=%s&sign=%s",
                    text, FROM, TO, APP_ID, salt, sign);

            httpPost.setEntity(new StringEntity(body));

            HttpResponse response = httpClient.execute(httpPost);         
            HttpEntity entity = response.getEntity();
            String responseJson = EntityUtils.toString(entity);

            JSONObject jsonObject = new JSONObject(responseJson);
            String translation = jsonObject.getJSONArray("trans_result").getJSONObject(0).getString("dst");

            System.out.println("Translation: " + translation);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Conclusion
    Through the Baidu Translation API, we can easily translate between Chinese and Spanish. In the program sample code developed using Java, the translation functions from Chinese to Spanish and Spanish to Chinese are implemented through HTTP requests and JSON parsing. I hope this article can help you understand how to use Baidu Translation API to translate between Chinese and Spanish.

The above is the detailed content of Implementation of Java Baidu Translation API for Chinese and Spanish translation. 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!