Home  >  Article  >  Java  >  Java Baidu Translation API realizes the application scenario of mutual translation between Chinese and Slovak

Java Baidu Translation API realizes the application scenario of mutual translation between Chinese and Slovak

PHPz
PHPzOriginal
2023-08-06 18:29:02514browse

Application scenarios for Java Baidu Translation API to realize mutual translation between Chinese and Slovak

With the development of globalization, communication between people has become more and more frequent. Language barriers have become an important issue in people's communication and interaction. In order to solve this problem, various translation tools have emerged. The Java Baidu Translation API is one of them. It realizes the function of mutual translation between Chinese and Slovak by calling the Baidu Translation API interface. This article will introduce how to use the Java Baidu Translation API to translate Chinese and Slovak into each other, and provide corresponding code examples.

First, we need to register an account on the Baidu Translation Open Platform and create an application. After successful registration, we can get an App ID and App key, which are used to call the Baidu Translation API interface.

Next, we need to introduce the relevant dependency packages of the Java Baidu Translation API. In the pom.xml file, add the following dependencies:

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

Then, we can create a TranslateUtil tool class to call the Baidu translation API interface for translation. The code is as follows:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.net.URLEncoder;

public class TranslateUtil {

    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static final String APP_ID = "your_app_id"; // 替换为自己的App ID
    private static final String SECURITY_KEY = "your_security_key"; // 替换为自己的App密钥

    /**
     * 调用百度翻译API进行翻译
     *
     * @param query 待翻译的字符串
     * @return 翻译结果
     */
    public static String translate(String query) {
        try {
            // 对待翻译的字符串进行URL编码
            String urlQuery = URLEncoder.encode(query, "UTF-8");

            // 构建请求URL
            String url = TRANS_API_HOST + "?q=" + urlQuery + "&from=auto&to=sk" +
                    "&appid=" + APP_ID + "&salt=1435660288&sign=" +
                    MD5Utils.md5(APP_ID + query + "1435660288" + SECURITY_KEY);

            // 发起HTTP请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            // 解析HTTP响应
            String responseStr = EntityUtils.toString(entity);
            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(responseStr);
            JSONArray transResultArray = (JSONArray) jsonObject.get("trans_result");
            JSONObject transResult = (JSONObject) transResultArray.get(0);
            String dst = (String) transResult.get("dst");

            // 关闭HTTP连接
            response.close();
            httpClient.close();

            return dst;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

In the above code, we call the Baidu Translation API interface to splice the string to be translated, App ID, key and other information into a URL, and initiate an HTTP request. We then parse the HTTP response, get the translation results and return them.

Finally, we can write a test class to test the TranslateUtil tool class. The code is as follows:

public class TranslateTest {

    public static void main(String[] args) {
        String query = "你好";
        String result = TranslateUtil.translate(query);
        System.out.println("中文:" + query);
        System.out.println("斯洛伐克语:" + result);
    }
}

In the test class, we can call the translate method of the TranslateUtil tool class, input a Chinese string to be translated, and output the translated Slovak string.

By running the test class, we can see the following output:

中文:你好
斯洛伐克语:Ahoj

The above are the steps and code examples for using the Java Baidu Translation API to translate Chinese and Slovak into each other. With the help of this API, we can achieve translation between more languages ​​and improve the convenience and efficiency of communication.

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

Statement:
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