集成框架 -- 阿里网关API

目录

      • 前言
      • 安全
      • 依赖
      • 示例
        • 测试
      • 涉及签名
        • 官网示例
        • 简化

前言

官网地址: 文档地址

外部接口,避免复杂配置,增加证书校验,可以选择API 网关

集成框架 -- 阿里网关API_第1张图片
看起来非常便宜
集成框架 -- 阿里网关API_第2张图片

安全

集成框架 -- 阿里网关API_第3张图片

安全性-链接地址

集成框架 -- 阿里网关API_第4张图片

两种建立方式
集成框架 -- 阿里网关API_第5张图片

直接用HTTPS 安全校验是可以跳过的,所以相比较HTTP HTTPS 可以任意切换

HTTPS 配置文档

配置完成之后

依赖

<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>

示例

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;

/**
 * 〈功能描述〉
* ----- : * * @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); } }

测试


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;




/**
 * 〈功能描述〉
* ----- : * * @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); } }

涉及签名

官网示例

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"));
    }
}
  1. 获取证书
  2. 运行keytools
  3. 获取证书密钥库
  4. 导入到资源文件
  5. 读取资源文件转换为url请求

简化




   /**
     * 初始化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();
    }






你可能感兴趣的:(Java,--,集成框架,java,前端,servlet)