首页 > 代码库 > java https 忽略证书 过期方式
java https 忽略证书 过期方式
package com.sprucetec.pop.product.util; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; //用于进行Https请求的HttpClient public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } }
package com.sprucetec.pop.product.upload; import java.io.*; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.Base64.Encoder; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Strings; import com.google.common.io.Files; import com.sprucetec.pop.product.model.OssDto; import com.sprucetec.pop.product.util.SSLClient; import com.sprucetec.pop.product.util.SSLHelper; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; @Component public class OssHttpUpload { @Autowired private OssDto ossDto; private List<String> fileExtensions; /** * 最大大小,字节 */ private long maxFileSize; public List<String> getFileExtensions() { return fileExtensions; } public void setFileExtensions(List<String> fileExtensions) { this.fileExtensions = fileExtensions; } public long getMaxFileSize() { return maxFileSize; } public void setMaxFileSize(long maxFileSize) { this.maxFileSize = maxFileSize; } //private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class); public static final int DEFAULT_SOCKET_TIMEOUT = 5000; public static final int DEFAULT_CONNECT_TIMEOUT = 5000; public static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 5000; public static final int HttpClientUtil_DEFAULT_CONNECT_TIMEOUT=5000; private static CloseableHttpClient httpClient = HttpClients.createDefault(); public OssHttpUpload(){ this.fileExtensions = new ArrayList<>(); fileExtensions.add("jpg"); fileExtensions.add("png"); fileExtensions.add("jpeg"); this.maxFileSize = 500 * 1024; } public Map<String, String> storeFile(MultipartFile[] uploadFiles) throws Exception { if (uploadFiles == null || uploadFiles.length == 0) { throw new IllegalArgumentException("请选择要上传的文件!"); } Map<String, String> mapOss = new HashMap<>(); String tag="pop"; String key="4dd5e404aab5e25e5d0c2a1d08f5346f"; long tokenTimeout=5000; long expires=System.currentTimeMillis()/1000+tokenTimeout*3600; long uid=0; String uname=""; String object=""; Map<String, String> mapHeader=null; for (int i = 0; i < uploadFiles.length; i++) { MultipartFile mFile = uploadFiles[i]; // 上传文件的原名(即上传前的文件名字) String originalFilename = null; if (null == mFile || mFile.isEmpty()) { throw new IllegalArgumentException("不能上传空文件!"); } originalFilename = mFile.getOriginalFilename(); String prefix = Files.getFileExtension(originalFilename); if (Strings.isNullOrEmpty(prefix) || !isPicFile(prefix.toLowerCase())) { throw new IllegalArgumentException("上传的图片类型错误!"); } if (mFile.getSize() > this.maxFileSize) { throw new IllegalArgumentException("上传文件大小超出系统限制"); } String randomFileName = UUID.randomUUID().toString() + "." + prefix.toLowerCase(); //开始上传 try { String extensionName= originalFilename.substring(originalFilename.lastIndexOf(".")); object="pop_"+ System.currentTimeMillis()+extensionName;; JSONArray jsonArray=new JSONArray(); mapHeader = this.createOssHeader(tag,key,expires,uid,uname,object,jsonArray); String url=ossDto.getOssUploadUrl()+"/api/binoss/uploadBinary"; //调用接口 //String responseJson= this.fileUploadByFile_UseHttp(url,mFile,mapHeader); String responseJson= this.fileUploadByFile_UseHttps2(url,mFile,mapHeader); JSONObject jsonObj = JSON.parseObject(responseJson); if(!jsonObj.getString("ret").equals("0")){ throw new Exception("图片" + originalFilename + "(第 " + (i + 1) + " 张)上传失败"); } String fid=""; if(jsonObj.getJSONObject("data")!=null){ fid=jsonObj.getJSONObject("data").getString("fid"); } mapOss.put("fid", fid); } catch (IOException e) { throw new Exception("系统错误,上传文件失败" + e.getMessage()); } } return mapOss; } // 创建header public static Map createOssHeader(String tag,String key,long expires,long uid,String uname,String object,JSONArray options) throws NoSuchAlgorithmException, UnsupportedEncodingException{ // token 用MD5加密 MessageDigest md5=MessageDigest.getInstance("MD5"); md5.update((tag+key+expires).getBytes("utf-8")); String token = new BigInteger(1, md5.digest()).toString(16); // 创建 headers Encoder urlBase64Encoder = Base64.getUrlEncoder(); Map http_oss_auth_map = new HashMap(); http_oss_auth_map.put("tag", tag); http_oss_auth_map.put("expires", expires); http_oss_auth_map.put("token", token); String HTTP_OSS_AUTH = urlBase64Encoder.encodeToString(JSON.toJSONString(http_oss_auth_map).getBytes("UTF-8")); Map http_oss_param_map = new HashMap(); http_oss_param_map.put("uid", uid); http_oss_param_map.put("uname", uname); http_oss_param_map.put("object", object); http_oss_param_map.put("options", options); String HTTP_OSS_PARAM = urlBase64Encoder.encodeToString(JSON.toJSONString(http_oss_param_map).getBytes("UTF-8")); Map extraHeader = new HashMap<String,String>(); extraHeader.put("Oss-Auth",HTTP_OSS_AUTH); extraHeader.put("Oss-Param",HTTP_OSS_PARAM); return extraHeader; } // 传文件 用https方式 public static String fileUploadByFile_UseHttps(String url, MultipartFile uploadFile, Map<String,String> extraHeader) throws FileNotFoundException,Exception{ HttpClient httpClient_oss = new SSLClient(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).setConnectTimeout(HttpClientUtil_DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).build()); httpPost.addHeader("Content-Type", "application/octet-stream"); httpPost.addHeader("Connection", "Keep-Alive"); httpPost.addHeader("user-agent", "MEICAI/WMC"); for (String key : extraHeader.keySet()) { httpPost.addHeader(key, extraHeader.get(key)); } //CloseableHttpResponse response = null; HttpResponse response=null; String responseString = null; try { if (uploadFile != null) { FileInputStream fis=(FileInputStream) uploadFile.getInputStream(); InputStreamEntity reqEntity = new InputStreamEntity( fis, -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httpPost.setEntity(reqEntity); } //response = httpClient.execute(httpPost); response=httpClient_oss.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { // try { // if (response != null) { // //response.close(); // //response. // } // } catch (IOException e) { // //log.warn("response is not closed"); // throw new RuntimeException(e.getMessage(), e); // } } return responseString; } // 传文件 用http方式 public static String fileUploadByFile_UseHttp(String url, MultipartFile uploadFile, Map<String,String> extraHeader) throws FileNotFoundException{ HttpPost httpPost = new HttpPost(url); httpPost.setConfig(RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).setConnectTimeout(HttpClientUtil_DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).build()); httpPost.addHeader("Content-Type", "application/octet-stream"); httpPost.addHeader("Connection", "Keep-Alive"); httpPost.addHeader("user-agent", "MEICAI/WMC"); for (String key : extraHeader.keySet()) { httpPost.addHeader(key, extraHeader.get(key)); } CloseableHttpResponse response = null; String responseString = null; try { if (uploadFile != null) { FileInputStream fis=(FileInputStream) uploadFile.getInputStream(); InputStreamEntity reqEntity = new InputStreamEntity( fis, -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httpPost.setEntity(reqEntity); } response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { try { if (response != null) { response.close(); } } catch (IOException e) { //log.warn("response is not closed"); throw new RuntimeException(e.getMessage(), e); } } return responseString; } // 传文件 用http方式 public static String fileUploadByFile_UseHttps2(String url, MultipartFile uploadFile, Map<String,String> extraHeader) throws FileNotFoundException{ SSLHelper sslHelper=new SSLHelper(); PoolingHttpClientConnectionManager pcm= sslHelper.GetPcm(); /** * 通过setSSLSocketFactory(sslsf)保证httpclient实例能发送Https请求 */ // CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(50) // .setMaxConnPerRoute(50).setDefaultRequestConfig(RequestConfig.custom() // .setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build()) // .build(); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).setConnectTimeout(HttpClientUtil_DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).build()).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).setConnectTimeout(HttpClientUtil_DEFAULT_CONNECT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT).build()); httpPost.addHeader("Content-Type", "application/octet-stream"); httpPost.addHeader("Connection", "Keep-Alive"); httpPost.addHeader("user-agent", "MEICAI/WMC"); for (String key : extraHeader.keySet()) { httpPost.addHeader(key, extraHeader.get(key)); } CloseableHttpResponse response = null; String responseString = null; try { if (uploadFile != null) { FileInputStream fis=(FileInputStream) uploadFile.getInputStream(); InputStreamEntity reqEntity = new InputStreamEntity( fis, -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); httpPost.setEntity(reqEntity); } //response = httpClient.execute(httpPost); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { try { if (response != null) { response.close(); } if(httpClient!=null){ httpClient.close(); } } catch (IOException e) { //log.warn("response is not closed"); throw new RuntimeException(e.getMessage(), e); } } return responseString; } private boolean isPicFile(String picPrefix) { return this.fileExtensions.contains(picPrefix); } }
java https 忽略证书 过期方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。