操作步骤
API 网关提供了一个 JAVA SDK,即 gateway-sdk。该 SDK 集成了加签、验签的逻辑,同时默认支持序列化和反序列化。使用该 SDK 接入调用 HTTP 服务的操作步骤如下:
引入 SDK
您需要在本地工程 pom.xml 中添加如下 SDK。
com.alipay.sofa
gateway-sdk
2.0.3
构建 request 对象
您需要构建 request 对象,用于组装请求,代码示例如下:publicclassParamPostRequestimplementsApiRequest{
// 请求参数
Map params =newHashMap<>();
// 请求header
Map headers =newHashMap<>();
privateString apiVersion ="1.0";
// downstream 的 uri
privateString path;
// 网关强制开启验签加签
privateboolean clientCheckSign =true;
@Override
publicString getPath(){
return path;
}
publicvoid setPath(String path){
this.path = path;
}
@Override
publicString getApiMethodName(){
return"test";
}
@Override
publicMap getBizParams(){
return params;
}
@Override
publicString getApiVersion(){
return apiVersion;
}
@Override
publicvoid setApiVersion(String apiVersion){
this.apiVersion = apiVersion;
}
@Override
publicString getRequestType(){
return"POST";
}
@Override
publicClass getResponseClass(){
returnParamResponse.class;
}
@Override
publicMap getHeaderParams(){
return headers;
}
@Override
publicboolean checkSign(){
return clientCheckSign;
}
publicvoid setClientCheckSign(boolean clientCheckSign){
this.clientCheckSign = clientCheckSign;
}
}
构建 response 对象
您需要构建 response 对象,用于接收响应,代码示例如下:publicclassParamResponseextendsApiResponse{
privateString path;
publicString getPath(){
return path;
}
publicvoid setPath(String path){
this.path = path;
}
}
创建 apiClient
使用获取的 AK、SK、host 创建一个 apiClient,代码示例如下:privateString subAppAccessKey ="m9hoHiqtjylGjqXC";
privateString subAppSecretKey ="sxCg1uk6UjGARr1hPswE0W2KHe86YvhX";
privateString gatewayUrl ="https://5jzkcn0idt3w4czs.apigateway.inc.alipay.net";
//开启数据加密后,在调用请阅的 API 时必须传入应用的 AK 和 SK 完成加签。
privateApiClient apiClient;
@Before
publicvoid initClient(){
// 初始化请求客户端
ApiSecretKey apiSecretKey =newApiSecretKey(subAppAccessKey, subAppSecretKey);
List secretKeys =newArrayList<>();
secretKeys.add(apiSecretKey);
apiClient =newDefaultApiClient(gatewayUrl, secretKeys);
}
发起调用请求
apiClient 配置完成之后,即可对 API 发起调用。响应会自动序列化到 response 对象里,直接使用即可,代码示例如下:@Test
publicvoid testNoSignHttp(){
ParamPostRequest request =newParamPostRequest();
request.setPath("simple/demo");
// 是否对响应进行签名校验
request.setClientCheckSign(false);
ApiResponse response = apiClient.execute(request);
System.out.println(JSON.toJSONString(response));
}