使用Open API访问CBS接口(不用SDK,java版)

2023-09-14 16:05:16 浏览数 (4)

前提,首先获取到腾讯云的AK SK

登录腾讯云官网控制台后访问

https://console.cloud.tencent.com/cam/capi

可以看到

这个密钥对即是我们访问API的钥匙。

新建一个main函数,整个API请求的签名共分为五个步骤

1.拼接请求串。

2.拼接待签名串

3.计算签名

4.拼接Authorization

5.请求API

代码语言:javascript复制
public class CBSAPI {

	private final static Charset UTF8 = StandardCharsets.UTF_8;	
	private final static String SECRET_ID = "改成自己的";	
	private final static String SECRET_KEY = "改成自己的";
	private final static String CT_JSON = "application/json; charset=utf-8";

	public static byte[] hmac256(byte[] key, String msg) throws Exception {
		Mac mac = Mac.getInstance("HmacSHA256");
		SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
		mac.init(secretKeySpec);
		return mac.doFinal(msg.getBytes(UTF8));
	}

	public static String sha256Hex(String s) throws Exception {
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		byte[] d = md.digest(s.getBytes(UTF8));
		return DatatypeConverter.printHexBinary(d).toLowerCase();
	}

	public static void main(String[] args) throws Exception {
		String service = "cbs";
		String host = "cbs.tencentcloudapi.com";
		String region = "ap-beijing";
		String action = "DescribeDisks";
		String version = "2017-03-12";
		String algorithm = "TC3-HMAC-SHA256";
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 注意时区,否则容易出错
		sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
		String date = sdf.format(new Date(Long.valueOf(timestamp   "000")));

		// ************* 步骤 1:拼接规范请求串 *************
		String httpRequestMethod = "POST";
		String canonicalUri = "/";
		String canonicalQueryString = "";
		String canonicalHeaders = "content-type:application/json; charset=utf-8n"   "host:"   host   "n"
				  "x-tc-action:"   action.toLowerCase()   "n";
		String signedHeaders = "content-type;host;x-tc-action";

		String payload = "{"Limit": 100}";
		String hashedRequestPayload = sha256Hex(payload);
		String canonicalRequest = httpRequestMethod   "n"   canonicalUri   "n"   canonicalQueryString   "n"
				  canonicalHeaders   "n"   signedHeaders   "n"   hashedRequestPayload;
		System.out.println(canonicalRequest);

		// ************* 步骤 2:拼接待签名字符串 *************
		String credentialScope = date   "/"   service   "/"   "tc3_request";
		String hashedCanonicalRequest = sha256Hex(canonicalRequest);
		String stringToSign = algorithm   "n"   timestamp   "n"   credentialScope   "n"   hashedCanonicalRequest;
		System.out.println(stringToSign);

		// ************* 步骤 3:计算签名 *************
		byte[] secretDate = hmac256(("TC3"   SECRET_KEY).getBytes(UTF8), date);
		byte[] secretService = hmac256(secretDate, service);
		byte[] secretSigning = hmac256(secretService, "tc3_request");
		String signature = DatatypeConverter.printHexBinary(hmac256(secretSigning, stringToSign)).toLowerCase();
		System.out.println(signature);

		// ************* 步骤 4:拼接 Authorization *************
		String authorization = algorithm   " "   "Credential="   SECRET_ID   "/"   credentialScope   ", "
				  "SignedHeaders="   signedHeaders   ", "   "Signature="   signature;
		System.out.println(authorization);

		TreeMap<String, String> headers = new TreeMap<String, String>();
		headers.put("Authorization", authorization);
		headers.put("Content-Type", CT_JSON);
		headers.put("Host", host);
		headers.put("X-TC-Action", action);
		headers.put("X-TC-Timestamp", timestamp);
		headers.put("X-TC-Version", version);
		headers.put("X-TC-Region", region);

		StringBuilder sb = new StringBuilder();
		sb.append("curl -X POST https://").append(host).append(" -H "Authorization: ").append(authorization)
				.append(""").append(" -H "Content-Type: application/json; charset=utf-8"").append(" -H "Host: ")
				.append(host).append(""").append(" -H "X-TC-Action: ").append(action).append(""")
				.append(" -H "X-TC-Timestamp: ").append(timestamp).append(""").append(" -H "X-TC-Version: ")
				.append(version).append(""").append(" -H "X-TC-Region: ").append(region).append(""").append(" -d '")
				.append(payload).append("'");
		System.out.println(sb.toString());
	}
}

生成后会得到一个curl命令。例如:

curl -X POST https://cbs.tencentcloudapi.com -H "Authorization: TC3-HMAC-SHA256 Credential=AKIDc7ORGrMkwvhEZic2FE0XvCIAsRp6C83u/2023-09-14/cbs/tc3_request, SignedHeaders=content-type;host;x-tc-action, Signature=162933d7a933f4e552888d0d65297061e5e36fd83b44318a45daad46dc21c256" -H "Content-Type: application/json; charset=utf-8" -H "Host: cbs.tencentcloudapi.com" -H "X-TC-Action: DescribeDisks" -H "X-TC-Timestamp: 1694676570" -H "X-TC-Version: 2017-03-12" -H "X-TC-Region: ap-beijing" -d '{"Limit": 100}'

测试一下访问:

正常通过。所以就可以在自己的代码中构造request请求来实现与API的调用了。

0 人点赞