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"}