评论

JAVA图片上传代码分享

Java图片上传实例代码

1.环境介绍:

代码环境 :17.0.8
本示例中使用了微信官方的SDK《wechatpay-apache-httpclient》
地址:https://github.com/wechatpay-apiv3/wechatpay-apache-httpclient
需要参数:商户号、商户证书序列号、商户私钥(apiclient_key.pem)、APIV3秘钥。
以上参数请自行获取,可以参考这篇文档:https://developers.weixin.qq.com/community/develop/article/doc/0004ec050348e066198c2c4a051c13 (已获取作者同意引用)

2.代码部分:

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.WechatPayUploadHttpPost;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivateKey;


public class test08upLoad {

    //新建一个可以关闭的请求
    CloseableHttpClient httpClient;

    @Test
    public void imageUpLoad() throws IOException, URISyntaxException {
        // 加载商户私钥(privateKey:私钥字符串)
        String key = "私钥(apiclient_key.pem文件内容)";
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(key.getBytes("utf-8")));

        // 加载平台证书(mchId:商户号,mchSerialNo:商户证书序列号,apiV3Key:V3密钥)
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials("商户号", new PrivateKeySigner("商户证书序列号", merchantPrivateKey)),"APIV3密钥".getBytes("utf-8"));

        // 初始化httpClient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant("商户号", "商户证书序列号", merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();

        // 上传图片
        String filePath = "D:\\test\\4m.jpg";
        URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
        File file = new File(filePath);


        try (FileInputStream ins1 = new FileInputStream(file)) {
            // 计算sha256
            String sha256 = DigestUtils.sha256Hex(ins1);
            try (InputStream ins2 = new FileInputStream(file)) {
                // 发送请求传递图片名称、sha256值和图片二进制流
                HttpPost request = new WechatPayUploadHttpPost.Builder(uri)
                        .withImage(file.getName(), sha256, ins2)
                        .build();
                CloseableHttpResponse response = httpClient.execute(request);
                try {
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                    } else if (statusCode == 204) {
                        System.out.println("success");
                    } else {
                        System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                        throw new IOException("request failed");
                    }
                } finally {
                    response.close();
                    httpClient.close();
                }
            }
        }
    }


}
最后一次编辑于  2023-12-27  
点赞 1
收藏
评论

3 个评论

  • Fly
    Fly
    2023-12-21

    直接加载私钥文件可以使用

    PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
            new FileInputStream("/path/to/apiclient_key.pem"));
    


    2023-12-21
    赞同 1
    回复
  • 小楼昨夜又东风
    小楼昨夜又东风
    09-26
    httpClient.execute(request)报错了org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
    
    09-26
    赞同
    回复
  • Fly
    Fly
    2023-12-21

    注释不是写的很详细,有问题可以留言

    2023-12-21
    赞同
    回复
登录 后发表内容