阿里云机器翻译基于JAVA签名校验使用示例教程-阿里云开发者社区

开发者社区> taro_秋刀鱼> 正文

阿里云机器翻译基于JAVA签名校验使用示例教程

简介: 阿里云会对每个访问的请求进行身份验证,所以无论使用 HTTP 还是 HTTPS 协议提交请求,都需要在请求中包含签名(Signature)信息。通过使用 Access Key ID 和 Access Key Secret 进行对称加密的方法来验证请求的发送者身份。阿里云提供了多种语言的 SDK 及第三方 SDK,可以免去您对签名算法进行编码的麻烦。这里以机器翻译通用版API接口为例演示具体的Java自签名实现Code。
+关注继续查看

Step By Step

1、pom.xml

   <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.collections/google-collections -->
        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>1.0-rc2</version>
        </dependency>
    </dependencies>

2、工具类:UrlUtil

import java.net.URLEncoder;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class UrlUtil {
    private static Logger logger = Logger.getLogger(UrlUtil.class);
    private final static String CHARSET_UTF8 = "utf8";
    /**
     *
     * @param url
     * @return
     */
    public static String urlEncode(String url) {
        if (!StringUtils.isEmpty(url)) {
            try {
                url = URLEncoder.encode(url, "UTF-8");
            } catch (Exception e) {
                logger.warn("Url encode error:" + e.getMessage());
            }
        }
        return url;
    }
    public static String generateQueryString(Map<String, String> params, boolean isEncodeKV) {
        StringBuilder canonicalizedQueryString = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (isEncodeKV)
                canonicalizedQueryString.append(percentEncode(entry.getKey())).append("=")
                        .append(percentEncode(entry.getValue())).append("&");
            else
                canonicalizedQueryString.append(entry.getKey()).append("=")
                        .append(entry.getValue()).append("&");
        }
        if (canonicalizedQueryString.length() > 1) {
            canonicalizedQueryString.setLength(canonicalizedQueryString.length() - 1);
        }
        return canonicalizedQueryString.toString();
    }
    public static String percentEncode(String value) {
        try {
            // 使用URLEncoder.encode编码后,将"+","*","%7E"做替换即满足 API规定的编码规范
            return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
                    .replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (Exception e) {
            //不可能发生的异常
        }
        return "";
    }
}

3、工具类:SignatureUtils

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
public class SignatureUtils {
    private final static String CHARSET_UTF8 = "utf8";
    private final static String ALGORITHM = "UTF-8";
    private final static String SEPARATOR = "&";
    public static Map<String, String> splitQueryString(String url)
            throws URISyntaxException, UnsupportedEncodingException {
        URI uri = new URI(url);
        String query = uri.getQuery();
        final String[] pairs = query.split("&");
        TreeMap<String, String> queryMap = new TreeMap<String, String>();
        for (String pair : pairs) {
            final int idx = pair.indexOf("=");
            final String key = idx > 0 ? pair.substring(0, idx) : pair;
            if (!queryMap.containsKey(key)) {
                queryMap.put(key, URLDecoder.decode(pair.substring(idx + 1), CHARSET_UTF8));
            }
        }
        return queryMap;
    }
    public static String generate(String method, Map<String, String> parameter,
                                  String accessKeySecret) throws Exception {
        String signString = generateSignString(method, parameter);
        System.out.println("signString---"+signString);
        byte[] signBytes = hmacSHA1Signature(accessKeySecret + "&", signString);
        String signature = newStringByBase64(signBytes);
        System.out.println("signature---"+signature);
        if ("POST".equals(method))
            return signature;
        return URLEncoder.encode(signature, "UTF-8");
    }
    public static String generateSignString(String httpMethod, Map<String, String> parameter)
            throws IOException {
        TreeMap<String, String> sortParameter = new TreeMap<String, String>();
        sortParameter.putAll(parameter);
        String canonicalizedQueryString = UrlUtil.generateQueryString(sortParameter, true);
        if (null == httpMethod) {
            throw new RuntimeException("httpMethod can not be empty");
        }
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(httpMethod).append(SEPARATOR);
        stringToSign.append(percentEncode("/")).append(SEPARATOR);
        stringToSign.append(percentEncode(canonicalizedQueryString));
        return stringToSign.toString();
    }
    public static String percentEncode(String value) {
        try {
            return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
                    .replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (Exception e) {
        }
        return "";
    }
    public static byte[] hmacSHA1Signature(String secret, String baseString)
            throws Exception {
        if (StringUtils.isEmpty(secret)) {
            throw new IOException("secret can not be empty");
        }
        if (StringUtils.isEmpty(baseString)) {
            return null;
        }
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), ALGORITHM);
        mac.init(keySpec);
        return mac.doFinal(baseString.getBytes(CHARSET_UTF8));
    }
    public static String newStringByBase64(byte[] bytes)
            throws UnsupportedEncodingException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        return new String(Base64.encodeBase64(bytes, false), CHARSET_UTF8);
    }
    public static void main(String[] args) {
        String str = "GET&%2F&AccessKeyId%3DCd***eHJuMOrT%26Action%3DDescribeInstances%26Format%3DJSON%26RegionId%3Dcn-hangzhou%26SignatureMethod%3DHMAC-SHA1%26SignatureNonce%3D9fdf288**36082ebef%26SignatureVersion%3D1.0%26Timestamp%3D2015-12-21T09%253A05%253A44Z%26Version%3D2014-05-26";
        byte[] signBytes;
        try {
            signBytes = SignatureUtils.hmacSHA1Signature("byc****6HQmH" + "&", str.toString());
            String signature = SignatureUtils.newStringByBase64(signBytes);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

4、Main方法

import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

public class Demo1 {
    private static String getQueryUrl(Map<String, String> param, String accessKeyId, String secret) throws Exception {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        simpleDateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
        String timestamp = simpleDateFormat.format(date);
        Map<String, String> publicParam = Maps.newHashMap();

        publicParam.put("AccessKeyId", accessKeyId);
        publicParam.put("Format", "json");
        publicParam.put("SignatureMethod", "Hmac-SHA1");
        publicParam.put("SignatureNonce", UUID.randomUUID().toString());
        publicParam.put("SignatureVersion", "1.0");
        publicParam.put("Timestamp", timestamp);
        publicParam.put("Version", "2018-10-12");
        publicParam.put("RegionId", "cn-hangzhou");

        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                publicParam.put(entry.getKey(), entry.getValue());
            }
        }

        String s = SignatureUtils.generateSignString("POST", publicParam);
        byte[] signBytes;
        signBytes = SignatureUtils.hmacSHA1Signature(secret + "&", s);
        String signature = SignatureUtils.newStringByBase64(signBytes);

        publicParam.put("Signature", signature);

        String url = "https://mt.cn-hangzhou.aliyuncs.com/?";
        //对参数进行url编码
        for (Map.Entry<String, String> entry : publicParam.entrySet()) {
            publicParam.put(entry.getKey(), URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
        }
        //拼接请求url
        for (Map.Entry<String, String> entry : publicParam.entrySet()) {
            url = url + entry + "&";
        }
        //去掉最后一个&
        url = url.substring(0, url.length() - 1);
        return url;
    }

    public static void main(String[] args) {
        try {
            Map<String, String> map = Maps.newHashMap();
            map.put("Action", "TranslateGeneral");
            map.put("FormatType","text");
            map.put("Scene","general");
            map.put("SourceLanguage","zh");
            map.put("TargetLanguage","en");
            map.put("SourceText","北京欢迎你");

            // access_key_id, access_key_secret  获取参考链接:https://yq.aliyun.com/articles/693979?spm=a2c4e.11155435.0.0.319326a2bKJ90g
            String accessKeyId = "LTAIOZZg********";
            String secret = "v7CjUJCMk7j9aK****************";
            String url = getQueryUrl(map, accessKeyId, secret);

            // 使用生成的 URL 创建POST请求
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            HttpClient httpclient = HttpClients.createDefault();

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

5、Result

{"RequestId":"81B8EE71-FBA6-47A1-B200-F7B911111111","Data":{"Translated":"Welcome to Beijing"},"Code":"200"}

参考链接

机器翻译通用版调用指南
阿里云新版人脸识别基于JAVA签名校验使用示例教程

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
10027 0
Android中Java反射技术的使用示例
MainActivity如下: package cn.testreflect; import java.lang.reflect.Constructor; import java.
553 0
《JavaScript和jQuery实战手册(原书第2版)》——3.2节教程:使用条件语句
本节书摘来自华章社区《JavaScript和jQuery实战手册(原书第2版)》一书中的第3章,第3.2节教程:使用条件语句,作者:David Sawyer McFarland,更多章节内容可以访问云栖社区“华章社区”公众号查看
1115 0
JavaScript 测试及校验工具
JavaScript 是一款强大的广泛运用于现代Web站点及应用的脚本语言。作为一个技艺精湛的 Web 开发者,掌握JavaScript可以增强用户的使用体验,提供交互及富客户端等功能。
786 0
使用sdk签名方法详解
 说明:   现在使用服务端支付SDK签名比较方便快捷,推荐大家使用,服务端SDK下载地址【点击查看】  签名主要有三种方式:      pageExecute:唤起网页进行支付方式,用于手机网站,电脑网站支付接口。
830 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,阿里云优惠总结大概有三种登录方式: 登录到ECS云服务器控制台 在ECS云服务器控制台用户可以更改密码、更换系.
13841 0
Java校招学习之路的经验总结——《我的Java打怪日记》
不论科班还是非科班,不论大一还是研二,都可以看看,希望对你有所帮助。
8720 0
[Java 安全]消息摘要与数字签名
消息摘要 算法简述 定义 它是一个唯一对应一个消息或文本的固定长度的值,它由一个单向Hash加密函数对消息进行作用而产生。如果消息在途中改变了,则接收者通过对收到消息的新产生的摘要与原摘要比较,就可知道消息是否被改变了。
951 0
+关注
taro_秋刀鱼
博客园主页:https://home.cnblogs.com/u/taro/
237
文章
9
问答
来源圈子
更多
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载