
11

阿里云API网关调用示例
source link: https://wakzz.cn/2018/12/07/java/%E9%98%BF%E9%87%8C%E4%BA%91API%E7%BD%91%E5%85%B3%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

阿里云API网关调用示例
祈雨的博客
2018-12-07
SDK调用
maven
<dependency>
<groupId>com.aliyun.api.gateway</groupId>
<artifactId>sdk-core-java</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
api层
import com.alibaba.cloudapi.sdk.client.ApacheHttpClient;
import com.alibaba.cloudapi.sdk.enums.HttpMethod;
import com.alibaba.cloudapi.sdk.enums.Scheme;
import com.alibaba.cloudapi.sdk.model.ApiRequest;
import com.alibaba.cloudapi.sdk.model.ApiCallback;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
public class HttpApiClient extends ApacheHttpClient{
/**
* 初始化请求参数
* @param isHttps 是否为https请求
* @param host
* @param appKey
* @param appSecret
*/
public HttpApiClient(boolean isHttps, String host, String appKey, String appSecret){
// HTTP/HTTPS Client init
HttpClientBuilderParams httpParam = new HttpClientBuilderParams();
httpParam.setHost(host);
httpParam.setAppKey(appKey);
httpParam.setAppSecret(appSecret);
if(isHttps){
initHttpsClient(httpParam);
} else {
initHttpClient(httpParam);
}
super.init(httpParam);
}
/**
* 初始化HTTP请求参数
* @param httpParam
*/
private void initHttpClient(HttpClientBuilderParams httpParam){
httpParam.setScheme(Scheme.HTTP);
}
/**
* 初始化HTTPS请求参数
* @param httpsParam
*/
private void initHttpsClient(HttpClientBuilderParams httpsParam){
httpsParam.setScheme(Scheme.HTTPS);
/**
* HTTPS request use DO_NOT_VERIFY mode only for demo
* Suggest verify for security
*/
X509TrustManager xtm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] x509Certificates = new X509Certificate[0];
return x509Certificates;
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
}
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
httpsParam.setSslSocketFactory(sslContext.getSocketFactory());
httpsParam.setX509TrustManager(xtm);
httpsParam.setHostnameVerifier(DO_NOT_VERIFY);
}
/**
* 同步接口
* @param body
* @return
*/
public ApiResponse send(byte[] body) {
String path = "/test/send.json";
ApiRequest request = new ApiRequest(HttpMethod.POST_BODY , path, body);
return sendSyncRequest(request);
}
/**
* 异步接口
* @param body
* @param apiCallback
*/
public void sendAnsy(byte[] body, ApiCallback apiCallback) {
String path = "/test/send.json";
ApiRequest request = new ApiRequest(HttpMethod.POST_BODY , path, body);
sendAsyncRequest(request, apiCallback);
}
}
服务层
import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.model.ApiCallback;
import com.alibaba.cloudapi.sdk.model.ApiRequest;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestApiService {
private static Logger log = LoggerFactory.getLogger(TestApiService.class);
private final HttpApiClient httpApiClient;
/**
* 初始化请求参数
* @param isHttps 是否为https请求
* @param host
* @param appKey
* @param appSecret
*/
public TestApiService(boolean isHttps, String host, String appKey, String appSecret){
this.httpApiClient = new HttpApiClient(isHttps, host, appKey, appSecret);
}
/**
* 同步接口
* @return
*/
public JSONObject send(){
String body = "{}";
ApiResponse response = this.httpApiClient.send(body.getBytes(SdkConstant.CLOUDAPI_ENCODING));
JSONObject result = JSONObject.parseObject(new String(response.getBody()));
return result;
}
/**
* 异步接口
*/
public void sendAnsy(){
String body = "{}";
this.httpApiClient.sendAnsy(body.getBytes(SdkConstant.CLOUDAPI_ENCODING), new ApiCallback() {
@Override
public void onFailure(ApiRequest request, Exception e) {
log.error(e.getMessage(),e);
}
@Override
public void onResponse(ApiRequest request, ApiResponse response) {
JSONObject result = JSONObject.parseObject(new String(response.getBody()));
log.info(result.toJSONString());
}
});
}
public static void main(String[] args) {
boolean isHttps = false;
String host = "";
String appKey = "";
String appSecret = "";
TestApiService service = new TestApiService(isHttps, host, appKey, appSecret);
service.sendAnsy();
}
}
手动请求调用
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
public class TestHttpClient {
private static final String HTTP_METHOD = "POST";
private static final String ACCEPT_VALUE = "application/json;charset=utf-8";
private static final String CONTENT_TYPE_VALUE = "application/json;charset=utf-8";
private static final String HmacSHA256 = "HmacSHA256";
public static void main(String[] args) throws Exception {
test();
}
private static void test() throws Exception {
String appKey = "";
String appSecret = "";
String host = "";
String url = "";
String body = "";
// 计算签名
Date date = new Date();
String uuid = UUID.randomUUID().toString();
String sign = getSign(appKey, appSecret, date, url, body, uuid);
HttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(host + url);
// 设置请求header
post.setHeader("date", String.valueOf(date.getTime()));
post.setHeader("accept", ACCEPT_VALUE);
post.setHeader("content-type", CONTENT_TYPE_VALUE);
post.setHeader("x-ca-key", appKey);
post.setHeader("x-ca-signature", sign);
post.setHeader("x-ca-timestamp", String.valueOf(date.getTime()));
post.setHeader("x-ca-nonce", uuid);
post.setHeader("content-md5", getBaseMD5(body));
post.setHeader("x-ca-signature-headers", "x-ca-nonce,x-ca-timestamp,x-ca-key");
StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8);
post.setEntity(entity);
System.out.println("entity:" + entity);
HttpResponse response = httpClient.execute(post);
System.out.println("response:" + response);
System.out.println("Content: " + IOUtils.toString(response.getEntity().getContent()));
}
/**
* 获取验签值
*/
private static String getSign(String appKey, String appSecret, Date date, String url, String body, String uuid) throws Exception {
String contentMD5 = getBaseMD5(body);
String formatDate = String.valueOf(date.getTime());
String headers = getSignHeaders(appKey, date, uuid);
StringBuilder builder = new StringBuilder();
builder.append(HTTP_METHOD).append("\n");
builder.append(ACCEPT_VALUE).append("\n");
builder.append(contentMD5).append("\n");
builder.append(CONTENT_TYPE_VALUE).append("\n");
builder.append(formatDate).append("\n");
builder.append(headers);
builder.append(url);
String stringToSign = builder.toString();
Mac hmacSha256 = Mac.getInstance(HmacSHA256);
byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, HmacSHA256));
byte[] value = hmacSha256.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(value);
}
/**
* 输入内容md5后再base64
*/
private static String getBaseMD5(String body) {
byte[] md5Bytes = DigestUtils.md5(body.getBytes(StandardCharsets.UTF_8));
final Base64 base64 = new Base64();
return new String(base64.encode(md5Bytes));
}
/**
* 组装需要进行sign验签的header
*/
private static String getSignHeaders(String appKey, Date date, String uuid) {
long timestamp = date.getTime();
Map<String, String> map = new TreeMap<>();
map.put("x-ca-key", appKey);
map.put("x-ca-nonce", uuid);
map.put("x-ca-timestamp", String.valueOf(timestamp));
StringBuilder builder = new StringBuilder();
for (String key : map.keySet()) {
String value = map.getOrDefault(key, "");
String header = String.format("%s:%s\n", key, value);
builder.append(header);
}
return builder.toString();
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK