腾讯机器翻译非官方Demo(Java版)

        这几天试用一下腾讯的机器翻译,按照官方文档操作,一直都未成功。在网友的帮助下,再加上很多次的尝试,终于能调用成功了。在此将代码贴出来,作为非官方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 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 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);
        }
    }
}

 

你可能感兴趣的:(踩坑记录)