请求需要登录的接口

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>com.antherd</groupId>
            <artifactId>sm-crypto</artifactId>
            <version>0.3.2</version>
        </dependency>

        <!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <!--http客户端-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>



        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.5.1</version>
        </dependency>

keypair类

/**
 * 基于SM2的秘钥对
 * (本项目中配置的,自己使用可根据自己的需求进行更换)
 */
public class keypair {

    /**
     * 公钥
     */
    public static String PUBLIC_KEY = "04298364ec840088475eae92a591e01284d1abefcda348b47eb324bb521bb03b0b2a5bc393f6b71dabb8f15c99a0050818b56b23f31743b93df9cf8948f15ddb54";

    /**
     * 私钥
     */
    public static String PRIVATE_KEY = "3037723d47292171677ec8bd7dc9af696c7472bc5f251b2cec07e65fdef22e25";

    /**
     * SM4的对称秘钥(生产环境需要改成自己使用的)
     * 16 进制字符串,要求为 128 比特
     */
    public static String KEY = "0123456789abcdeffedcba9876543210";

}

CryptogramUtill类

import cn.hutool.log.Log;
import com.antherd.smcrypto.sm2.Sm2;
import com.antherd.smcrypto.sm3.Sm3;
import com.antherd.smcrypto.sm4.Sm4;
import com.antherd.smcrypto.sm4.Sm4Options;

/**
 * 加密工具类,本框架目前使用 https://github.com/antherd/sm-crypto 项目中一些加解密方式
 * 使用小伙伴需要过等保密评相关,请在此处更改为自己的加密方法,或加密机,使用加密机同时需要替换公钥,私钥在内部无法导出,提供加密的方法
 */
public class CryptogramUtil {

    private static final Log log = Log.get();

    /**
     * 加密方法(Sm2 的专门针对前后端分离,非对称秘钥对的方式,暴露出去的公钥,对传输过程中的密码加个密)
     *
     * @param str 待加密数据
     * @return 加密后的密文
     */
    public static String doSm2Encrypt (String str) {
        return Sm2.doEncrypt(str, keypair.PUBLIC_KEY);
    }

    /**
     * 解密方法
     * 如果采用加密机的方法,用try catch 捕捉异常,返回原文值即可
     * @param str 密文
     * @return 解密后的明文
     */
    public static String doSm2Decrypt (String str) {
        // 解密
        return Sm2.doDecrypt(str, keypair.PRIVATE_KEY);
    }

    /**
     * 加密方法
     * @param str 待加密数据
     * @return 加密后的密文
     */
    public static String doEncrypt (String str) {
        // SM4 加密  cbc模式
        Sm4Options sm4Options4 = new Sm4Options();
        sm4Options4.setMode("cbc");
        sm4Options4.setIv("fedcba98765432100123456789abcdef");
        return Sm4.encrypt(str, keypair.KEY, sm4Options4);
    }

    /**
     * 解密方法
     * 如果采用加密机的方法,用try catch 捕捉异常,返回原文值即可
     * @param str 密文
     * @return 解密后的明文
     */
    public static String doDecrypt (String str) {
        // 解密,cbc 模式,输出 utf8 字符串
        Sm4Options sm4Options8 = new Sm4Options();
        sm4Options8.setMode("cbc");
        sm4Options8.setIv("fedcba98765432100123456789abcdef");
        String docString =  Sm4.decrypt(str, keypair.KEY, sm4Options8);
        if (docString.equals("")) {
            log.warn(">>> 字段解密失败,返回原文值:{}", str);
            return str;
        } else {
            return docString;
        }
    }

    /**
     * 纯签名
     * @param str 待签名数据
     * @return 签名结果
     */
    public static String doSignature (String str) {
        return Sm2.doSignature(str, keypair.PRIVATE_KEY);
    }

    /**
     * 验证签名结果
     * @param originalStr 签名原文数据
     * @param str 签名结果
     * @return 是否通过
     */
    public static boolean doVerifySignature (String originalStr, String str) {
        return Sm2.doVerifySignature(originalStr, str, keypair.PUBLIC_KEY);
    }

    /**
     * 通过杂凑算法取得hash值,用于做数据完整性保护
     * @param str 字符串
     * @return hash 值
     */
    public static String doHashValue (String str) {
        return Sm3.sm3(str);
    }

}

HttpRequestUtil类

import com.alibaba.fastjson.JSON;
import net.minidev.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 */
public class HttpRequestUtil {

    private String DATA_ENCODING = "DataEncoding";
    private String CONTENT_TYPE = "Content-Type";
    private String APPLICATION_JSON = "application/json";
    public CloseableHttpClient httpClient;
    public HttpServletRequest request;

    public HttpRequestUtil() {
    }

    /**
     * 免登录请使用该构造方法创建httpClient对象,
     * 调用系统中的接口,不需要再次使用账户密码进行登录,不支持第三方接口
     *
     * @param hostIP  这个参数特别重要,为了给请求设置domain,具体看下面第3小点
     * @param request 当次前端发起的请求
     */
    public HttpRequestUtil(HttpServletRequest request, String hostIP) {
        //设置http的cookie,把前端请求的sessionID加入到httpUtil中
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", request.getSession().getId());
        //设置cookie的domain信息,否则sessionID无法生效
        //String ipAddr = IpUtils.getIpAddr(request);
        cookie.setDomain(hostIP);
        /**
         * 设置cookie的Path信息,为全局的url,如:如http://shuizhu.com/api/xxx/xxx,该path就是"/api"
         * 如果没有该path,下面的代码最好写上
         */
        cookie.setPath(request.getContextPath());
        cookieStore.addCookie(cookie);
        this.request = request;
        //生成httpClient
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }

    /**
     * 需要登录的方式,生成httpClient工具对象
     *
     * @param loginUrl 登录地址
     * @param reqMap   存储账号密码的map,如:
     *                 {
     *                 "userName":"admin"
     *                 ,"password":"123456"
     *                 }
     *                 创建对象:
     *                 Map<String,Object> reqMap = new HashMap<>();
     *                 reqMap.put("userName","admin");
     *                 reqMap.put("password","123456");
     */
    public HttpRequestUtil(String loginUrl, Map<String, Object> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(loginUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(EntityUtils.toString(response.getEntity()));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String getToken (String loginUrl, Map<String, Object> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(loginUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            HttpResponse response = httpClient.execute(httpPost);
            String s = EntityUtils.toString(response.getEntity());
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(s);
            String data = jsonObject.getString("data");
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户发起http请求,这里只演示post类型的请求
     *
     * @param url    请求的路径
     * @param reqMap 请求的参数
     * @return 接口响应的JSON数据
     */
    public String doPost(String url, Map<String, String> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        //设置请求连接参数等
        httpPost.setConfig(requestConfig);
        //设置请求数据类型为JSON
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        //设置编码
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        CloseableHttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}

测试HttpTest类

import cn.hutool.http.HttpRequest;

import java.util.HashMap;
import java.util.Map;

public class HttpTest {
    public static void main(String[] args) {
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("account", "superAdmin");
        reqMap.put("password", CryptogramUtil.doSm2Encrypt("123456"));
        HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
        String token = httpRequestUtil.getToken("http://localhost:82/login", reqMap);
        String value = "Bearer " + token;
        String resultStr = HttpRequest.get("http://localhost:82/sysOrg/page")
                .header("Authorization", value)
                .execute()
                .body();
        System.out.println(resultStr);
    }

}
posted @ 2023-03-29 21:35  紫川先生  阅读(72)  评论(0)    收藏  举报