Table of contents
Preface
Official website address: Document address
External interface, avoid complex configuration, add certificate verification, you can choose API gateway
looks very cheap
Safety
Security- Link Address
Two ways to create
If you use HTTPS directly, the security check can be skipped, so compared to HTTP, HTTPS can be switched at will.
After the configuration is completed
rely
<dependency>
<groupId>com.aliyun.api.gateway</groupId>
<artifactId>sdk-core-java</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.7.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
Example
package com.demo.unit.api;
import com.alibaba.cloudapi.sdk.client.ApacheHttpClient;
import com.alibaba.cloudapi.sdk.constant.SdkConstant;
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.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
/**
* 〈功能描述〉<br>
* ----- :
*
* @author xsc
* @date 2022/9/26 10:04
*/
@Slf4j
public class HttpApiClient extends ApacheHttpClient {
/**
* 初始化请求参数
* @param isHttps
*/
public HttpApiClient(boolean isHttps, String host, String appKey, String appSecret){
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);
}
/**
* 同步接口
* @param body
*/
public ApiResponse send(String body,String path) {
byte[] bytes = body.getBytes(SdkConstant.CLOUDAPI_ENCODING);
ApiRequest request = new ApiRequest(HttpMethod.POST_BODY , path, bytes);
System.out.println("request = " + JSON.toJSONString(request));
return sendSyncRequest(request);
}
}
test
package com.demo.unit;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.fastjson.JSONObject;
import com.demo.unit.api.HttpApiClient;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* 〈功能描述〉<br>
* ----- :
*
* @author xsc
* @date 2022/9/26 10:04
*/
@SpringBootTest
public class Demo4 {
private final static String path = "";
private final static String HOST = "";
private final static String appKey ="";
private final static String appSecret ="";
private HttpApiClient httpApiClient;
@Test
public void getTest() {
if (httpApiClient==null){
this.httpApiClient= new HttpApiClient(true, HOST, appKey, appSecret);
}
String body = "{}";
ApiResponse send = httpApiClient.send(body,path);
JSONObject result = JSONObject.parseObject(new String(send.getBody()));
System.out.println("send = " + result);
}
}
involves signature
Official website example
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
public class HttpClientWithClientCert {
private final static String PFX_PATH = "/Users/fred/temp/cert5/client.p12"; //客户端证书路径
private final static String PFX_PWD = "123456"; //客户端证书密码
public static String sslRequestGet(String url) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream instream = new FileInputStream(new File(PFX_PATH));
try {
keyStore.load(instream, PFX_PWD.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
, new String[] {
"TLSv1" } // supportedProtocols ,这里可以按需要设置
, null // supportedCipherSuites
, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpGet httpget = new HttpGet(url);
//httpget.addHeader("host", "integration-fred2.fredhuang.com");// 设置一些heander等
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");//返回结果
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("java.home"));
System.out.println(sslRequestGet("https://integration-fred2.fredhuang.com"));
}
}
- Get certificate
- Run keytools
- Get certificate keystore
- Import into resource file
- Read resource files and convert them into url requests
simplify
/**
* 初始化HTTPS请求参数
*
* @param httpsParam
*/
private void initHttpsClient(HttpClientBuilderParams httpsParam) {
httpsParam.setScheme(Scheme.HTTPS);
// httpsParam.setRegistry(getRegistry());
}
private Registry<ConnectionSocketFactory> getRegistry() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
try {
registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE).build();
registryBuilder.register("https", new SSLConnectionSocketFactory(loadCustomKeyStore(), new DefaultHostnameVerifier()));
} catch (Exception e) {
throw new RuntimeException("HttpClientUtil init failure !", e);
}
return registryBuilder.build();
}
private SSLContext loadCustomKeyStore() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, URISyntaxException, KeyManagementException {
SSLContextBuilder sslBuilder = SSLContexts.custom();
File file = new File(Objects.requireNonNull(HttpApiClient.class.getClassLoader().getResource("签名证书java路径")).toURI());
return sslBuilder.loadTrustMaterial(file, "签名密码".toCharArray()).build();
}