Home >Java >javaTutorial >Utilize Java Baidu Translation API to achieve fast and accurate translation between multiple languages
Use Java Baidu Translation API to achieve fast and accurate translation between multiple languages
With the accelerated development of globalization, communication between people has become increasingly frequent. However, communication between different languages remains a huge barrier. To solve this problem, translation technology has been widely used. In translation technology, machine translation has also developed into a common method.
Baidu Translation is one of the more widely used online translation services in China. By using Baidu Translation API, we can easily achieve fast and accurate translation between multiple languages in Java programs. This article will introduce in detail how to use the Java Baidu Translation API for translation and provide relevant code examples.
First, we need to apply for a developer account on the Baidu translation platform and create an application. When creating an application, we will obtain an API Key and Secret Key, which will be used to authorize API access.
Next, we use Java for programming. First, we need to import the necessary library files. In this example, we use Apache HttpClient to send HTTP requests and Json-lib to parse the returned JSON data. Therefore, we need to add relevant dependencies in the project's build file.
import net.sf.json.JSONObject; import net.sf.json.JSONArray; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List;
Next, we define a Translate class, which contains two methods:
public class Translate { // 百度翻译API地址 private static final String TRANSLATE_API_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate"; // 百度翻译API密钥 private static final String API_KEY = "YOUR_API_KEY"; // 百度翻译API密钥 private static final String SECRET_KEY = "YOUR_SECRET_KEY"; /** * 将文本从指定语言翻译为目标语言 * * @param text 待翻译文本 * @param sourceLang 源语言 * @param targetLang 目标语言 * @return 翻译结果 */ public static String translate(String text, String sourceLang, String targetLang) { try { HttpClient httpClient = HttpClients.createDefault(); // 构建请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("q", text)); params.add(new BasicNameValuePair("from", sourceLang)); params.add(new BasicNameValuePair("to", targetLang)); params.add(new BasicNameValuePair("appid", API_KEY)); params.add(new BasicNameValuePair("salt", String.valueOf(System.currentTimeMillis()))); params.add(new BasicNameValuePair("sign", getSign(text))); HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); // 发送POST请求 HttpPost httpPost = new HttpPost(TRANSLATE_API_URL); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); // 解析返回的JSON数据 String jsonString = EntityUtils.toString(response.getEntity(), "UTF-8"); JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray transArray = jsonObject.getJSONArray("trans_result"); JSONObject transObj = transArray.getJSONObject(0); String translation = transObj.getString("dst"); return translation; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 生成签名 * * @param text 待翻译文本 * @return 签名 */ private static String getSign(String text) { String sign = API_KEY + text + String.valueOf(System.currentTimeMillis()) + SECRET_KEY; return MD5.encode(sign); } }
In the above code, the translate method receives three parameters: the text to be translated, the source language and Target language. It first sends a POST request to Baidu Translation API through HttpClient, then parses the returned JSON data, and finally returns the translation results.
The getSign method is used to generate a signature, which concatenates the API Key, the text to be translated, the current timestamp and the Secret Key, and then encrypts it using the MD5 encryption algorithm.
Using the above Translate class, we can translate easily. The following is a usage example:
public class Main { public static void main(String[] args) { String text = "Hello world!"; String sourceLang = "en"; String targetLang = "zh"; String translation = Translate.translate(text, sourceLang, targetLang); System.out.println("翻译结果:" + translation); } }
By running the above code, we can translate the English "Hello world!" into Chinese and output it on the console. Of course, you can also adjust it according to your own needs to achieve more complex translation functions.
To sum up, using the Java Baidu Translation API can quickly and accurately achieve translation between multiple languages. Through the above code examples, we can see that using Baidu Translation API can easily implement translation functions in Java programs. I hope this article can help you understand and use Baidu Translation API!
The above is the detailed content of Utilize Java Baidu Translation API to achieve fast and accurate translation between multiple languages. For more information, please follow other related articles on the PHP Chinese website!