访问阿里api网关接口客户端demo,java实现源码,其他语言可参考
上一篇文章 《阿里api网关接口创建、发布、授权、调试》 中,介绍了3个典型接口的创建并在阿里控制台调试完成,地址:https://blog.csdn.net/a704397849/article/details/89421342
- app用户账号密码登录 ,认证方式: OpenID Connect(模式:获取授权api) & 阿里云APP
- app用户查询用户信息 ,认证方式: OpenID Connect(模式:业务api) & 阿里云APP
- 设备(如:智能故事机)获取播放的资源 ,认证方式: 阿里云APP
本篇介绍 用java实现的客户端如何去访问这3个阿里api网关接口。
阿里官方有提供客户端demo,有java,Android,object-c,php 等语言,但是没有C的实现,github 搜索 aliyun/api-gateway-demo-sign ,可以看到官方提供的哪些语言访问api网关的客户端demo
既然官方已经提供了java语言demo了,那么本篇文章的意义又在哪里呢?
其他语言的demo我没有去看,看了下java的demo源码,虽然封装的比较多,但是可以使用,程序我也跑通了,但是官方没有提供C语言的代码,公司应用前端不仅仅有Android ,IOS,还有C语言开发的设备端。让C语言开发工程师去看java demo,而且还是封装的比较多的java代码,简直不要太坑!所以呢,为了方便和各个前端能快速开发调试api网关接口,我将官方提供的java demo代码 简化提取出来,虽然不是C实现,但是过程还是比较简单、清晰的,参考一下能快速开发出C的客户端实现,其他语言也可以参考这个代码。
AliApiGateWayTest 源码: (代码中用到的 fastjson 和 base64包,在下面有下载链接,如果有需要下载即可)
package test;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author zx
*/
public class AliApiGateWayTest {
public static String appKey = "xxxxxxxx";//用自己的appKey
public static String appSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";//用自己的appSecret
public static String Host = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-cn-shenzhen.alicloudapi.com";//用自己的Host
public static String url = "http://" + Host;
public static void main(String[] args) throws Exception {
//登录
userLogin();
/**
* 查询用户信息
* 参数token值是 userLogin() 登录成功 返回的token
*/
// userQueryPlaylist("eyJhbGciOiJSUzI1NiIsImtpZCI6IjAzNDFhMTFiNTg4NzQ0OWE5MmQxYzU4N2MyZDQ0NzMxIn0.eyJqdGkiOiJoT2xXb2Z3YmE4aUlvZkVPdzhkNlV3IiwiaWF0IjoxNTU1NTc5MTgxLCJleHAiOjE1NTU2NjU1ODEsIm5iZiI6MTU1NTU3OTEyMSwic3ViIjoiWU9VUl9TVUJKRUNUIiwiYXVkIjoiWU9VUl9BVURJRU5DRSIsInVzZXJJZCI6IjExMTcxNyJ9.Kiggtsa--lpXnVqmIRNH7Or0iREwqNk50uKivrL948Z8Jw4_LtBvEHSivhW6i4R8ZSkmNGxIrmbHFcg6NNTlkLjPGSDrqQ0nxyoh_9yKwh11Jof1kOrJo7dgV7MlqdWP2CPG4bDvIbxwMRwVoqcrShdpe-z7uuiotCGJ79Ed5vLXP9GrSn8IroXrFpENRRtp3N_X3wlWOaTpIZIxLRPCy3iHBnXItviVsH9_-sK40_dwSNGFoBcmjI_nFbsnvAFOwxBApUopPgb7T_3D3weVPH8mkgCpWp386el_P4GWJuGm5jSQ0QmWVTLQxKepPpT5HWkW3mnhBxM3KMomAhcZjA");
//设备获取播放资源
// deviceAudioQuery();
}
//用户登录
static void userLogin() throws Exception {
String path = "/user/login";
/*TEST RELEASE PRE */
String stage = "TEST";
String timestamp = System.currentTimeMillis() + "";
String nonce = UUID.randomUUID().toString().replaceAll("-", "");
Http http = new Http(url+path);
//Body内容
JSONObject jo = new JSONObject();
jo.put("phone","188xxxxxxxx");
jo.put("password","123456");
String body = jo.toString();
//body内容用 md5 base64 加密
String contentMd5 = "";
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(body.getBytes("UTF-8"));
byte[] enbytes = new Base64().encode(md.digest());
contentMd5 = new String(enbytes);
//headers
Map<String,String> headers = new HashMap<String, String>();
// headers.put("Host",Host);
// headers.put("gateway_channel","http");
//(必填)根据期望的Response内容类型设置
headers.put("Accept", "application/json");
//(可选)Body MD5,服务端会校验Body内容是否被篡改,建议Body非Form表单时添加此Header
headers.put("Content-MD5",contentMd5 );
//(POST/PUT请求必选)请求Body内容格式
headers.put("Content-Type", "application/text; charset=UTF-8");
headers.put("X-Ca-Timestamp",timestamp);
headers.put("X-Ca-Key",appKey);
headers.put("X-Ca-Stage",stage);
headers.put("X-Ca-Nonce",nonce );
// headers.put("X-Ca-Signature-Headers","X-Ca-Timestamp,X-Ca-Request-Mode,X-Ca-Key,X-Ca-Stage");
headers.put("X-Ca-Signature-Headers","X-Ca-Key,X-Ca-Nonce,X-Ca-Timestamp");
String stringToSign=
"POST" + "\n" +
"application/json" + "\n" +
contentMd5 + "\n" +
"application/text; charset=UTF-8" + "\n" +
"" + "\n" +
"X-Ca-Key:" + appKey + "\n" +
"X-Ca-Nonce:" + nonce + "\n" +
"X-Ca-Timestamp:" + timestamp + "\n" +
path;
String sign = "";
try {
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = appSecret.getBytes("UTF-8");
hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes("UTF-8"))),"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
headers.put("X-Ca-Signature",sign);
//设置http的请求头
http.setRequestHeaders(headers);
//http.requestHeadersToISO_8859_1();
//http post 请求
String res = http.post(body);
System.out.println("response body:\n"+new String(res.getBytes("ISO-8859-1"), "UTF-8"));
}
//用户查询用户信息
static void userQueryPlaylist(String token) throws Exception {
String path = "/user/info/query" + "/" + token;
/*TEST RELEASE PRE */
String stage = "TEST";
String timestamp = System.currentTimeMillis() + "";
String nonce = UUID.randomUUID().toString().replaceAll("-", "");
Http http = new Http(url+path);
//Body内容
JSONObject jo = new JSONObject();
jo.put("id",110);
String body = jo.toString();
//body内容用 md5 base64 加密
String contentMd5 = "";
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(body.getBytes("UTF-8"));
byte[] enbytes = new Base64().encode(md.digest());
contentMd5 = new String(enbytes);
//headers
Map<String,String> headers = new HashMap<String, String>();
//headers.put("Host",Host);
//headers.put("X-Ca-Request-Mode","debug");
//headers.put("gateway_channel","http");
//(必填)根据期望的Response内容类型设置
headers.put("Accept", "application/json");
//(可选)Body MD5,服务端会校验Body内容是否被篡改,建议Body非Form表单时添加此Header
headers.put("Content-MD5",contentMd5 );
//(POST/PUT请求必选)请求Body内容格式
headers.put("Content-Type", "application/text; charset=UTF-8");
headers.put("X-Ca-Timestamp",timestamp);
headers.put("X-Ca-Key",appKey);
headers.put("X-Ca-Stage",stage);
headers.put("X-Ca-Nonce",nonce );
headers.put("X-Ca-Signature-Headers","X-Ca-Key,X-Ca-Nonce,X-Ca-Timestamp");
String stringToSign=
"POST" + "\n" +
"application/json" + "\n" +
contentMd5 + "\n" +
"application/text; charset=UTF-8" + "\n" +
"" + "\n" +
"X-Ca-Key:" + appKey + "\n" +
"X-Ca-Nonce:" + nonce + "\n" +
"X-Ca-Timestamp:" + timestamp + "\n" +
path;
String sign = "";
try {
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = appSecret.getBytes("UTF-8");
hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes("UTF-8"))),"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
headers.put("X-Ca-Signature",sign);
//设置http的请求头
http.setRequestHeaders(headers);
//http.requestHeadersToISO_8859_1();
//http post 请求
String res = http.post(body);
System.out.println("response body:\n"+new String(res.getBytes("ISO-8859-1"), "UTF-8"));
}
//设备获取播放资源
static void deviceAudioQuery() throws Exception {
String path = "/device/audio/query";
/*TEST RELEASE PRE */
String stage = "TEST";
String timestamp = System.currentTimeMillis() + "";
String nonce = UUID.randomUUID().toString().replaceAll("-", "");
Http http = new Http(url+path);
//Body内容
String body = "";
//body内容用 md5 base64 加密
String contentMd5 = "";
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(body.getBytes("UTF-8"));
byte[] enbytes = new Base64().encode(md.digest());
contentMd5 = new String(enbytes);
//headers
Map<String,String> headers = new HashMap<String, String>();
//headers.put("Host",Host);
//headers.put("X-Ca-Request-Mode","debug");
//headers.put("gateway_channel","http");
//(必填)根据期望的Response内容类型设置
headers.put("Accept", "application/json");
//(可选)Body MD5,服务端会校验Body内容是否被篡改,建议Body非Form表单时添加此Header
headers.put("Content-MD5",contentMd5 );
//(POST/PUT请求必选)请求Body内容格式
headers.put("Content-Type", "application/text; charset=UTF-8");
headers.put("X-Ca-Timestamp",timestamp);
headers.put("X-Ca-Key",appKey);
headers.put("X-Ca-Stage",stage);
headers.put("X-Ca-Nonce",nonce );
headers.put("X-Ca-Signature-Headers","X-Ca-Key,X-Ca-Nonce,X-Ca-Timestamp");
String stringToSign=
"POST" + "\n" +
"application/json" + "\n" +
contentMd5 + "\n" +
"application/text; charset=UTF-8" + "\n" +
"" + "\n" +
"X-Ca-Key:" + appKey + "\n" +
"X-Ca-Nonce:" + nonce + "\n" +
"X-Ca-Timestamp:" + timestamp + "\n" +
path;
String sign = "";
try {
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = appSecret.getBytes("UTF-8");
hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes("UTF-8"))),"UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
headers.put("X-Ca-Signature",sign);
//设置http的请求头
http.setRequestHeaders(headers);
//http.requestHeadersToISO_8859_1();
//http post 请求
String res = http.post(body);
System.out.println("response body:\n"+new String(res.getBytes("ISO-8859-1"), "UTF-8"));
}
}
上面代码中用到的Http请求工具类源码: (注,不一定要用我提供的http工具,自己常用的http工具也是可以的)
package test;
import com.alibaba.fastjson.JSON;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* Http协议工具
*
* @author
*/
public class Http {
// 文本协议Content-type
public static final String text = "text/plain;charset=UTF-8";
// 标准的POST协议Content-type
public static final String post = "application/x-www-form-urlencoded;charset=UTF-8";
public enum ContentType {
asf("video/x-ms-asf"), avi("video/avi"), mpg("ivideo/mpeg"), gif("image/gif"), jpg("image/jpeg"), bmp("image/bmp"), png("image/png"), wav(
"audio/wav"), mp3("audio/mpeg3"), html("text/html"), txt("text/plain"), zip("application/zip"), doc("application/msword"), xls(
"application/vnd.ms-excel"), rtf("application/rtf"), all("application/octet-stream");
private String type;
private ContentType(String type) {
this.type = type;
}
public String getType() {
return type;
}
@Override
public String toString() {
return type;
}
}
protected String httpURL;
protected URL url;
// 请求头参数
protected Map<String, String> requestProperty = new HashMap<String, String>();
// 连接超时时间
protected int connectTimeout =