騰訊機器翻譯非官方Demo(Java版)
阿新 • • 發佈:2019-02-06
這幾天試用一下騰訊的機器翻譯,按照官方文件操作,一直都未成功。在網友的幫助下,再加上很多次的嘗試,終於能呼叫成功了。在此將程式碼貼出來,作為非官方Demo供大家作為參考。
package com.frank.test; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.http.StatusLine; 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 javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayOutputStream; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; /** * Created by Administrator on 2018/7/6. */ public class TencentTrans { private static final Charset UTF_8 = StandardCharsets.UTF_8; // 請填寫自己的SecretId private static final String SECRET_ID = "AKIDaaaaaaaaaaaaaaaaaaa"; // 請填寫自己的SecretKey private static final String SECRET_KEY = "Rksoebbbbbbbbbbbbbbb"; public static void main(String[] args) throws Exception { // 確定引數名的排序 // List<String> paramNameList = Lists.newArrayList(); // paramNameList.add("ProjectId"); // paramNameList.add("Source"); // paramNameList.add("SourceText"); // paramNameList.add("Target"); // // paramNameList.add("Action"); // paramNameList.add("Timestamp"); // paramNameList.add("Nonce"); // paramNameList.add("SecretId"); // paramNameList.add("Version"); // paramNameList.add("Region"); // Collections.sort(paramNameList); // System.out.println("paramNameList=" + paramNameList); // Action, Nonce, ProjectId, Region, SecretId, Source, SourceText, Target, Timestamp, Version Map<String, String> paramMap = Maps.newLinkedHashMapWithExpectedSize(10); paramMap.put("Action", "TextTranslate"); paramMap.put("Nonce", String.valueOf(RandomUtils.nextInt(10, 10000))); paramMap.put("ProjectId", "0");// 請填寫自己的ProjectId paramMap.put("Region", "ap-shanghai"); paramMap.put("SecretId", SECRET_ID); paramMap.put("Source", "en"); paramMap.put("SourceText", "Broadband speeds in UK slip down global league table"); paramMap.put("Target", "zh"); // 此處的時間戳要格外注意,是Unix時間戳 paramMap.put("Timestamp", String.valueOf(System.currentTimeMillis() / 1000)); paramMap.put("Version", "2018-03-21"); // 構造簽名信息 StringBuilder builder = new StringBuilder(); for (String key : paramMap.keySet()) { // 若輸入引數中包含下劃線,則需要將其轉換為“.” builder.append('&').append(key).append('=').append(paramMap.get(key).replace('_', '.')); } builder = builder.deleteCharAt(0); System.out.println("請求字串:" + builder.toString()); String str = "GETtmt.tencentcloudapi.com/?" + builder.toString(); str = Base64.encodeBase64String(hmacSha1(str, SECRET_KEY)); System.out.println("簽名串:" + str); str = URLEncoder.encode(str, UTF_8.toString()); System.out.println("簽名串編碼後:" + str); // 構造url builder = new StringBuilder(); String value = null; for (String key : paramMap.keySet()) { // 若輸入引數中包含下劃線,則需要將其轉換為“.” value = URLEncoder.encode(paramMap.get(key).replace('_', '.'), "UTF-8"); builder.append('&').append(key).append('=').append(value); } builder.append("&Signature=").append(str); String url = "https://tmt.tencentcloudapi.com/?" + builder.deleteCharAt(0).toString(); System.out.println("url=" + url); HttpGet get = new HttpGet(url); String result = null; try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(get); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { StatusLine sl = response.getStatusLine(); System.out.println("響應狀態碼:" + sl.getStatusCode() + ",響應資訊:" + sl.getReasonPhrase()); if (sl.getStatusCode() == 200) { IOUtils.copy(response.getEntity().getContent(), baos); result = new String(baos.toByteArray(), 0, baos.size(), UTF_8); // 去除換行符 result = result.replaceAll("\\r\\n", "").replaceAll("\\n", ""); System.out.println("返回響應結果:" + result); } } if (result == null) { return; } JSONObject resp = JSONObject.parseObject(result).getJSONObject("Response"); if (resp.get("Error") != null) { JSONObject err = resp.getJSONObject("Error"); System.out.println("ErrorCode: " + err.getString("Code") + ", ErrorMessage: " + err.getString("Message")); } else { System.out.println("譯文:" + resp.getString("TargetText")); } } public static byte[] hmacSha1(String src, String key) { try { SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); return mac.doFinal(src.getBytes(UTF_8)); } catch (Exception e) { throw new RuntimeException(e); } } }