最近写微信API的“上传临时素材接口”时,正好遇到该需求,经百度解决完毕后整理发出。
主逻辑参照下链接完成,这已经是一个好用的demo:构建multipart/form-data实现文件上传 - _herbert - 博客园构建multipart/form-data实现文件上传 通常文件上传都是通过form表单中的file控件,并将form中的content-type设置为multipart/form-data。现在我们https://www.cnblogs.com/yfrs/p/uploadbyjavacode.html在此基础上加入https请求的实现。下面内容的请求体格式与上文略有不同,是我参考微信API进行修改后的结果。希望能够帮助到大家。
package com.hstech.util.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.*; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.cert.X509Certificate; import java.util.UUID; public class FileUploadUtil { private static final Logger log = LoggerFactory.getLogger(FileUploadUtil.class); public static String postUploadSSL(String url, File file, String fileName) { StringBuilder result = new StringBuilder(); try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); // 构建请求头 conn.setRequestMethod("POST"); conn.setRequestProperty("accept", "* private static class TrustAnyTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } private static class TrustAnyHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)