微信退款SpringBoot读取resource下的证书

近期做了一个微信支付退款接口,需要证书双向验证,测试的时候证书暂时放在resource下,上图

起初MyConfig中我是这样,在本机IDE中运行没有问题

import org.springframework.util.ResourceUtils; 
 
public MyConfig() throws Exception {
        File file = (ResourceUtils.getFile("classpath:config/apiclient_cert.p12"));
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

但到Linux服务器的docker中运行就IO异常了,查阅资料可能原因是内嵌web容器访问的是jar包,

解决方法1:

import org.apache.commons.io.IOUtils;
 
public InputStream getCertStream() {
        try {
            InputStream certStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("config/apiclient_cert.p12");
            this.certData = IOUtils.toByteArray(certStream);
            certStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

解决方法2:

org.springframework.core.io.ClassPathResource;
 
public InputStream getCertStream() {
          try {
            ClassPathResource classPathResource = new ClassPathResource("config/apiclient_cert.p12");
            //获取文件流
            InputStream certStream = classPathResource.getInputStream();
            this.certData = IOUtils.toByteArray(certStream);
            certStream.read(this.certData);
            certStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

来源于:

https://blog.csdn.net/xiaoxudong666/article/details/82192425

猜你喜欢

转载自blog.csdn.net/weixin_41888813/article/details/84994730
今日推荐