Cette rubrique présente un exemple complet en Java pour appeler l'API SingleSendMail de Direct Mail à l'aide de requêtes HTTP brutes avec une signature HMAC-SHA1.
Avant de commencer
Avant d'exécuter l'exemple, procédez comme suit :
Obtenez un AccessKey ID et un AccessKey Secret depuis la console Alibaba Cloud. Stockez-les dans les variables d'environnement
ALIBABA_CLOUD_ACCESS_KEY_IDetALIBABA_CLOUD_ACCESS_KEY_SECRET.Vérifiez une adresse d'expéditeur dans la console Direct Mail et définissez-la comme valeur du paramètre
AccountName.Ajoutez les dépendances suivantes à votre fichier
pom.xml:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
Pour plus d'informations sur la configuration des variables AccessKeySecret et AccessKeyId en tant que variables d'environnement, consultez la rubrique Configurer un AccessKey pour la vérification d'identité dans une variable d'environnement.
Pour obtenir les RegionIds des autres régions, reportez-vous à la rubrique Points de terminaison API.
Fonctionnement
L'exemple réalise les opérations suivantes :
Regroupe tous les paramètres d'API requis dans un objet
TreeMaptrié.Encode les paramètres au format URL, calcule une signature HMAC-SHA1 et l'ajoute à la requête.
Envoie la requête signée vers
https://dm.aliyuncs.comvia une requête HTTP POST.Affiche la réponse de l'API pour confirmer le succès de l'opération.
Exemple de requête
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
* &<Common request parameters>
*/
@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();
String result = httpRequestSendEmail(params);
System.out.println("Response: " + result);
System.out.println("Time elapsed: " + (System.currentTimeMillis() - start) + " ms");
}
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;
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("Status: " + response.getStatusLine().getStatusCode());
if (null != response){
result = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
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");
// Sender address (must be verified in the Direct Mail console)
private final static String AccountName = "test***@example.net";
// Recipient address
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 = "Test subject";
private final static String TagName = "Test 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;
}
/**
* Get the signature
*
* @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 String MAC_NAME = "HmacSHA1";
private static final String ENCODING = "UTF-8";
/**
* Use the HMAC-SHA1 signature method to sign encryptText
*
* @param encryptText The string to be signed
* @param encryptKey The key
* @return
* @throws Exception
*/
public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes(ENCODING);
// Construct a key from the given byte array. The second parameter specifies the name of a key algorithm.
SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
// Generate a Mac object for a specified Mac algorithm.
Mac mac = Mac.getInstance(MAC_NAME);
// Initialize the Mac object with the given key.
mac.init(secretKey);
byte[] text = encryptText.getBytes(ENCODING);
// Complete the Mac operation.
return mac.doFinal(text);
}
private static DateFormat daetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Get the UTC time as a string in the "yyyy-MM-dd HH:mm" format.<br />
* If the operation fails, null is returned.
*
* @return
*/
public static String getUTCTimeStr() {
// 1. Get the local time.
Calendar cal = Calendar.getInstance();
// 2. Get the time zone offset.
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
// 3. Get the daylight saving time offset.
int dstOffset = cal.get(Calendar.DST_OFFSET);
// 4. Subtract these offsets from the local time to get the UTC time.
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
String date = daetFormat.format(cal.getTime());
String[] strs = date.split(" ");
return strs[0] + "T" + strs[1] + "Z";
}
}
Voici un exemple de requête URL signée envoyée depuis la région Chine (Hangzhou).
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%20Language%20Chinese%20Website%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()!%3C%2Fh3%3E%3C%2Fbody%3E%3C%2Fhtml%3E%20%3Ca%25b%27%20%2B%20%2A%20%257E%3E%20Test%20email%20body.%20Your%20verification%20code%20for%20this%20registration%20is%3A%20123456&RegionId=cn-hangzhou&ReplyToAddress=true&Signature=1PysI0HsZeOEHqQ%3D&SignatureMethod=HMAC-SHA1&SignatureNonce=37161234-7747-419f-b433-bc4719504b01&SignatureVersion=1.0&Subject=Test%20subject&TagName=Test%20tag&Timestamp=2018-11-07T09%3A40%3A13Z&ToAddress=xxxxx%40example.net&Version=2015-11-23