使用hutool实现http的调用

http的调用方式有很多我这里选取了hutool工具包的封装方法进行调用,超级方便!!!

依赖:

<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.8.11</version>
		</dependency>

调用方法,因为我要使用到AES加密所以方法里调用了其他方法

package com.huixin.nursing.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class GetHis {
    private String baseUrl = "http://192.168.30.188:2001/integrationv2/api/nurse/";

    /**
     * 调用his 接口
     *
     * @param url  具体方法名
     * @param data 需要转成json对象
     * @return
     */
    public String sendHis(String url, String data) {
        String result = null;
        try {
            System.out.println("RestClient data: ------" + data);
            //AES加密参数
            String json = AesUtils.encryptHex(data);
            System.out.println("RestClient AES json: ------" + json);
            json = "{\"data\":\"" + json + "\"}";
            // 拼接完整的请求 URL
            String requestUrl = baseUrl + url;
            //发送请求
             result = HttpRequest.post(requestUrl).header("Content-Type", "application/json")
                    .body(json).execute().body();
            JSONObject jsonObject = JSONObject.parseObject(result);
            result=jsonObject.getString("data");
            Integer status=jsonObject.getInteger("status");
            //取data参数进行解密返回
            if(status==1){
                //状态为1时成功
                result = AesUtils.decryptHex(result);
                if (StringUtils.isEmpty(result)) {
                    System.err.println("Response is NULL -------------");
                }
            }else {
                //返回状态为0失败
                result=null;
            }
            System.out.println("RestClient result: ------" + result);
        } catch (Exception ex) {
            System.err.println("send----error" + ex.getMessage());
        }
        return result;
    }
}

下面是AES加密方式,返回16进制,
这里用到KEY和IV 其中的KEY最好使用16位的密钥,一般调用方都是取16位进行加密解密,节省双方处理上一些不必要的麻烦!!!(之前有踩坑过,我们这边超过16位,另外一方只取字符串的16位…)

package com.huixin.nursing.util;

import java.nio.charset.StandardCharsets;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AesUtils {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String IV = "1954682168745971";
    private static final String KEY = "dclcUVkjvPMZtIR39NzM4A==";
    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";


    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    /**
     * @description : AES加密返回16进制
     **/
    public static String encryptHex(String data) {
        try {
            // 从密钥字符串取前 16 个字符
            String keySubstring = KEY.substring(0, 16);
            byte[] keyBytes = keySubstring.getBytes(StandardCharsets.UTF_8);

            // 确保密钥长度为 16 字节
            keyBytes = padOrTrim(keyBytes, 16);
            SecretKeySpec aes = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, aes, iv);
            byte[] bytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return byteArrayToHexString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @description : AES解密返回16进制
     **/
    public static String decryptHex(String content) {
        try {
            // 从密钥字符串取前 16 个字符
            String keySubstring = KEY.substring(0, 16);
            byte[] keyBytes = keySubstring.getBytes(StandardCharsets.UTF_8);

            // 确保密钥长度为 16 字节
            keyBytes = padOrTrim(keyBytes, 16);
            SecretKeySpec aes = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, aes, iv);
            byte[] encryptedBytes = hexStringToByteArray(content);
            byte[] bytes = cipher.doFinal(encryptedBytes);
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static byte[] padOrTrim(byte[] input, int length) {
        if (input.length > length) {
            byte[] trimmed = new byte[length];
            System.arraycopy(input, 0, trimmed, 0, length);
            return trimmed;
        } else if (input.length < length) {
            byte[] padded = new byte[length];
            System.arraycopy(input, 0, padded, 0, input.length);
            return padded;
        } else {
            return input;
        }
    }


    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hex 十六进制字符串
     * @return 字节数组
     */
    public static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) throws Exception {
        //System.out.println(KEY.PadRight(16));
        String content = "c6d9e97a4c480d43a475a736f825b29484191b51f8893ce22d4cbecf38ba22b2ef3aaae1860d284ab183fab9305ddeb72ed6a1d519f4c6f9c9714365cd0f0b80073524c7654ddc457482514a59f3f8f77e7ee71fc89e309ade7b53b4a0cab933241d93a66a0fad377efc3bedf1ed45d6300358d4ba968f3e7777f826f6199326de57c55fce423491069af12b6f7e8bd4e8a55c3ad3f51aa59c4a52288e8ac395";
        String content2 = "{\" orgCode \":\" 310104000000 \",\" orgName \":\"徐汇区长桥街道社区卫生服务中心\",\"IDCardName\":\"310103193602190018\",\"Name\":\"111\"}";
        String encSrt = encryptHex(content2);
        System.out.println("加密----" + encSrt);
        System.out.println("解密后16进制--------" + decryptHex(encSrt));
        //System.out.println(encryptHex(content));
        //System.out.println("解密后64进制--------"+decryptBase64(encryptBase64(content)));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值