請求示例(Java)
更新時間:
API請求調(diào)用相關(guān)示例
package com.aliyun.test;
import codec.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
public class SampleAPI {
/**
* https://dm.aliyuncs.com/?Action=SingleSendMail
* &AccountName=test***@example.net
* &ReplyToAddress=true
* &AddressType=1
* &ToAddress=test1***@example.net
* &Subject=Subject
* &HtmlBody=body
* &<公共請求參數(shù)>
*/
@Test
public void testSingleSendMail() {
Map<String, Object> params = new TreeMap<String, Object>();
params.put("AccessKeyId", AccessKeyId);
params.put("Action", "SingleSendMail");
params.put("Format", Format);
params.put("RegionId", RegionId);
params.put("SignatureMethod", SignatureMethod);
params.put("SignatureNonce", UUID.randomUUID().toString());
params.put("SignatureVersion", SignatureVersion);
params.put("Timestamp", getUTCTimeStr());
params.put("Version", Version);
params.put("AccountName", AccountName);
params.put("AddressType", AddressType);
params.put("HtmlBody", HtmlBody);
params.put("ReplyToAddress", ReplyToAddress);
params.put("Subject", Subject);
params.put("TagName", TagName);
params.put("ToAddress", ToAddress);
Long start = System.currentTimeMillis();
httpRequestSendEmail(params);
System.out.println("耗時 : " + (System.currentTimeMillis() - start));
}
public String httpRequestSendEmail(Map<String, Object> params) {
String result = null;
try {
params.put("Signature", getSignature(prepareParamStrURLEncoder(params), method));
String param = prepareParamStrURLEncoder(params);
String url = protocol + "://" + host + "/?" + param;
System.out.println("-----url-----" + url);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = null;
if (method.equals(HttpMethod.GET)) {
HttpGet request = new HttpGet(url);
response = httpClient.execute(request);
} else {
HttpPost request = new HttpPost(url);
response = httpClient.execute(request);
}
System.out.println(response);
if (null != response){
result = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("-----httpRequestSendEmail result-----" + result);
return result;
}
private final static String protocol = "https";
private final static String host = "dm.aliyuncs.com";
private final static String AccessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
private final static String AccessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
//發(fā)信地址
private final static String AccountName = "test***@example.net";
//收信地址
private final static String ToAddress = "test1***@example.net";
private final static String Format = "JSON";
private final static String SignatureMethod = "HMAC-SHA1";
private final static String SignatureVersion = "1.0";
private final static String Version = "2015-11-23";
private final static String AddressType = "1";
private final static String RegionId = "cn-hangzhou";
private final static Boolean ReplyToAddress = Boolean.TRUE;
private final static String HtmlBody = "<html><body><h3>Test send to email! </h3></body></html>";
private final static String Subject = "測試主題";
private final static String TagName = "測試Tag";
private final static HttpMethod method = HttpMethod.POST;
public String prepareParamStrURLEncoder(Map<String, Object> params) {
try {
StringBuffer param = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (StringUtils.isBlank(entry.getKey()) || null == entry.getValue()) {
continue;
}
param.append(getUtf8Encoder(entry.getKey()) + "=" + getUtf8Encoder(entry.getValue().toString()) + "&");
}
return param.substring(0, param.lastIndexOf("&"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 獲取簽名
*
* @param param
* @param method
* @return
* @throws Exception
*/
private String getSignature(String param, HttpMethod method) throws Exception {
String toSign = method + "&" + URLEncoder.encode("/", "utf8") + "&"
+ getUtf8Encoder(param);
byte[] bytes = HmacSHA1Encrypt(toSign, AccessKeySecret + "&");
return Base64.encode(bytes);
}
private String getUtf8Encoder(String param) throws UnsupportedEncodingException {
return URLEncoder.encode(param, "utf8")
.replaceAll("\\+", "%20")
.replaceAll("\\*", "%2A")
.replaceAll("%7E", "~");
}
private static final對ring MAC_NAME = "HmacSHA1";
private static final String ENCODING = "UTF-8";
/**
* 使用 HMAC-SHA1 簽名方法對encryptText進行簽名
*
* @param encryptText 被簽名的字符串
* @param encryptKey 密鑰
* @return
* @throws Exception
*/
public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes(ENCODING);
//根據(jù)給定的字節(jié)數(shù)組構(gòu)造一個密鑰,第二參數(shù)指定一個密鑰算法的名稱
SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
//生成一個指定 Mac 算法的 Mac 對象
Mac mac = Mac.getInstance(MAC_NAME);
//用給定密鑰初始化 Mac 對象
mac.init(secretKey);
byte[] text = encryptText.getBytes(ENCODING);
//完成 Mac 操作
return mac.doFinal(text);
}
private static DateFormat daetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* 得到UTC時間,類型為字符串,格式為"yyyy-MM-dd HH:mm"<br />
* 如果獲取失敗,返回null
*
* @return
*/
public static String getUTCTimeStr() {
// 1、取得本地時間:
Calendar cal = Calendar.getInstance();
// 2、取得時間偏移量:
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// 3、取得夏令時差:
int dstOffset = cal.get(Calendar.DST_OFFSET);
// 4、從本地時間里扣除這些差量,即可以取得UTC時間:
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
String date = daetFormat.format(cal.getTime());
System.out.println("時間------" + date);
String[] strs = date.split(" ");
return strs[0] + "T" + strs[1] + "Z";
}
}
說明
如何將AccessKeySecret和AccessKeyId配置到環(huán)境變量中,請參考:在環(huán)境變量中配置身份驗證AccessKey
如何獲取其他區(qū)域的RegionId,請參考:API服務(wù)地址
——-杭州服務(wù)區(qū)域最后發(fā)出的URL請求示例如下——-
https://dm.aliyuncs.com/?AccessKeyId=xxxxxxx&AccountName=noreply%40xxxxxxxx.club&Action=SingleSendMail&AddressType=1&Format=JSON&HtmlBody=%3Chtml%3E%3Cbody%3E%3Cimg%20alt%3D%22Go%E8%AF%AD%E8%A8%80%E4%B8%AD%E6%96%87%E7%BD%91%22%20src%3D%22https%3A%2F%2Fstatic.studygolang.com%2Fimg%2Flogo1.png%22%20%3E%3Cimg%20alt%3D%22%22%20src%3D%22https%3A%2F%2Fgoss4.vcg.com%2Fcreative%2Fvcg%2F400%2Fnew%2FVCG211173951082.jpg%22%20%3E%3Ch3%3ETest%20send%20to%20email%20%EF%BC%88%EF%BC%89%EF%BC%81%3C%2Fh3%3E%3C%2Fbody%3E%3C%2Fhtml%3E%20%3Ca%25b%27%20%2B%20%2A%20%257E%3E%20%E6%B5%8B%E8%AF%95%E9%82%AE%E4%BB%B6%E6%AD%A3%E6%96%87%E3%80%82%E4%BD%A0%E6%AD%A4%E6%AC%A1%E7%94%B3%E8%AF%B7%E6%B3%A8%E5%86%8C%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E4%B8%BA%EF%BC%9A123456&RegionId=cn-hangzhou&ReplyToAddress=true&Signature=1PysI0HsZeOEHqQ%3D&SignatureMethod=HMAC-SHA1&SignatureNonce=37161234-7747-419f-b433-bc4719504b01&SignatureVersion=1.0&Subject=%E6%B5%8B%E8%AF%95%E4%B8%BB%E9%A2%98&TagName=%E6%B5%8B%E8%AF%95Tag&Timestamp=2018-11-07T09%3A40%3A13Z&ToAddress=xxxxx%40example.net&Version=2015-11-23
文檔內(nèi)容是否對您有幫助?