


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>
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 ""; } }
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); } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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. ...

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...

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...

Start Spring using IntelliJIDEAUltimate version...

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

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...

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...

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...
