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 "指定路径下生成文件成功!"; } }