企业微信下载素材库文件

1、创建MyX509TrustManager

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class MyX509TrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

}

2、实现下载具体代码

import net.sf.json.JSONObject;
import org.apache.commons.lang.exception.ExceptionUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;


public class WeiXinUtil {

    //微信的请求url
    // 获取access_token的接口地址(GET) 限200(次/天)

    public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}";//获取jsapi_ticket的接口地址(GET) 限200(次/天)

    public final static String jsapi_ticket_url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESSTOKEN";

    /*** 1.发起https请求并获取结果
     *
     *@paramrequestUrl 请求地址
     *@paramrequestMethod 请求方式(GET 、 POST)
     *@paramoutputStr 提交的数据
     *@returnJSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)*/

    public static String getBase64FromInputStream(InputStream in) {
        // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = in.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new String(Base64.getEncoder().encode(data));
    }
    /*** 2.发送https请求之获取临时素材
     *@paramrequestUrl
     *@paramsavePath 文件的保存路径,此时还缺一个扩展名
     *@return*@throwsException*/

    public static String getFile(String requestUrl, String savePath) throws Exception {
        //String path=System.getProperty("user.dir")+"/img//1.png";
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化

        TrustManager[] tm = {new MyX509TrustManager()};

        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

        sslContext.init(null, tm, new java.security.SecureRandom());
        //从上述SSLContext对象中得到SSLSocketFactory对象

        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL url = new URL(requestUrl);

        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();

        httpUrlConn.setSSLSocketFactory(ssf);

        httpUrlConn.setDoOutput(true);

        httpUrlConn.setDoInput(true);

        httpUrlConn.setUseCaches(false);//设置请求方式(GET/POST)

        httpUrlConn.setRequestMethod("GET");

        httpUrlConn.connect();//获取文件扩展名

        String ext = getExt(httpUrlConn.getContentType());

        savePath = savePath + ext;

        System.out.println("savePath" + savePath);//下载文件到f文件

        File file = new File(savePath);//获取微信返回的输入流


        InputStream in = httpUrlConn.getInputStream();//输出流,将微信返回的输入流内容写到文件中

       String str =  getBase64FromInputStream(in);

         in.close();//释放资源
        in = null;

        httpUrlConn.disconnect();
        return str;

    }

    private static String getExt(String contentType) {
        if ("image/jpeg".equals(contentType)) {
            return ".jpg";

        } else if ("image/png".equals(contentType)) {
            return ".png";

        } else if ("image/gif".equals(contentType)) {
            return ".gif";

        }
        return null;

    }
    public static String encryptToBase64(String filePath) {
        if (filePath == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
    public static InputStream baseToInputStream(final byte[] base64byte){
        ByteArrayInputStream stream = null;
        try {
            byte[] bytes1 = Base64.getEncoder().encode(base64byte);
            stream = new ByteArrayInputStream(bytes1);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return stream;
    }

    public static void main(String[] args) {
        try {

            String token ="cHsw7y4FHa6GVv5PfYForp6tyWKEaaAZmpnVD1AUBVoT2pHenckMFz_9rKskaGd3zsCB65NQMFZn1JvHZmrQgnxkS7xi6HuD3vcSUEyC4xmd63KMZnzFqIrvd4DjPK9LnTPh8duE41pKpRdXnNmGay6Gq-MpMD4SHbKa3pmLLA8rQzk3Q_HCV6Q2QV9ZhVkyo8uWrPgVSe6zXUPt5hJ05Ox3mfKDYMWXY3QRKjiX_gY";

          String str=  getFile("https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id=1F__jdg51M5FNk7JX1dnIVLFtpSoDTfxRearMcAwa5eeum6X0voedcQZrRbCjhi_i","d://a//test12");
/*
            String str=encryptToBase64("d://a//test12.jpg");



 */


            decryptByBase64(str,"d://a//test12345.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String decryptByBase64(String base64, String filePath) {
        if (base64 == null && filePath == null) {
            return "生成文件失败,请给出相应的数据。";
        }
        try {
            Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
        } catch (IOException e) {
            e.printStackTrace();


        }
        return "指定路径下生成文件成功!";
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值