帶jsk證書,請求https介面
阿新 • • 發佈:2018-11-12
首先是三個返回的實體類
BaseVo.java
package https2; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; public class BaseVo implements Serializable { private static final long serialVersionUID = 1L; public List<String> getField(Object model) { List<String> list = new ArrayList<String>(); java.lang.reflect.Method[] method = model.getClass().getDeclaredMethods();// 獲取物件所有方法 for (java.lang.reflect.Method m : method) { if (m.getName().startsWith("get")) {// 獲取get方法 Object o = null; try { o = m.invoke(model); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); }// 執行 if (o == null ) { list.add(""); } else { list.add(o.toString()); } } } return list; } }
PageVo.java
package https2; public class PageVo extends BaseVo { /** * */ private static final long serialVersionUID = 1L; private int current=1;//當前第幾頁 private int currentNum=1;//當前第幾頁 private int total;//總數 private int pages;//頁數 private int number = 15;//每頁多少條 private String column; private String order; public int getCurrentNum() { return currentNum; } public String getColumn() { return column; } public void setColumn(String column) { this.column = column; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int getCurrent() { return current; } public void setCurrent(int current) { this.current = current; this.currentNum = current; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; if(this.total%this.number==0){ this.pages = this.total / this.number; }else{ this.pages = this.total / this.number + 1; } } public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } }
ResultVo.java
package https2; public class ResultVo extends BaseVo{ /** * */ private static final long serialVersionUID = 1L; private String code; private String msg; private Object data; private PageVo page; public PageVo getPage() { return page; } public void setPage(PageVo page) { this.page = page; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
然後是一個工具類
package https2; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; public class HostnameVerifierUtil implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession arg1) { if("localhost".equals(hostname)){ return true; } else { return false; } } }
最後是https請求工具類
package https2; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import java.security.KeyStore; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import cn.smartercampus.core.vo.ResultVo; import com.alibaba.fastjson.JSON; public class HttpsPost { /** * 獲得KeyStore. * @param keyStorePath * 金鑰庫路徑 * @param password * 密碼 * @return 金鑰庫 * @throws Exception */ public static KeyStore getKeyStore(String password, String keyStorePath) throws Exception { // 例項化金鑰庫 KeyStore ks = KeyStore.getInstance("JKS"); // 獲得金鑰庫檔案流 FileInputStream is = new FileInputStream(keyStorePath); // 載入金鑰庫 ks.load(is, password.toCharArray()); // 關閉金鑰庫檔案流 is.close(); return ks; } /** * 獲得SSLSocketFactory. * @param password * 密碼 * @param keyStorePath * 金鑰庫路徑 * @param trustStorePath * 信任庫路徑 * @return SSLSocketFactory * @throws Exception */ public static SSLContext getSSLContext(String password, String keyStorePath, String trustStorePath) throws Exception { // 例項化金鑰庫 KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); // 獲得金鑰庫 KeyStore keyStore = getKeyStore(password, keyStorePath); // 初始化金鑰工廠 keyManagerFactory.init(keyStore, password.toCharArray()); // 例項化信任庫 TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); // 獲得信任庫 KeyStore trustStore = getKeyStore(password, trustStorePath); // 初始化信任庫 trustManagerFactory.init(trustStore); // 例項化SSL上下文 SSLContext ctx = SSLContext.getInstance("TLS"); // 初始化SSL上下文 ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); // 獲得SSLSocketFactory return ctx; } /** * 初始化HttpsURLConnection. * @param password * 密碼 * @param keyStorePath * 金鑰庫路徑 * @param trustStorePath * 信任庫路徑 * @throws Exception */ public static void initHttpsURLConnection(String password, String keyStorePath, String trustStorePath) throws Exception { // 宣告SSL上下文 SSLContext sslContext = null; // 例項化主機名驗證介面 HostnameVerifierUtil hnv = new HostnameVerifierUtil(); try { sslContext = getSSLContext(password, keyStorePath, trustStorePath); } catch (GeneralSecurityException e) { e.printStackTrace(); } if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext .getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(hnv); } /** * 傳送請求. * @param httpsUrl * 請求的地址 * @param xmlStr * 請求的資料 */ public static ResultVo post(String httpsUrl, String xmlStr) { HttpsURLConnection urlCon = null; try { urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection(); urlCon.setDoInput(true); urlCon.setDoOutput(true); urlCon.setRequestMethod("POST"); urlCon.setRequestProperty("Content-Length", String.valueOf(xmlStr.getBytes().length)); urlCon.setUseCaches(false); urlCon.getOutputStream().write(xmlStr.getBytes("UTF-8")); urlCon.getOutputStream().flush(); urlCon.getOutputStream().close(); BufferedReader in = new BufferedReader(new InputStreamReader( urlCon.getInputStream())); String line; StringBuffer resultStr = new StringBuffer(); while ((line = in.readLine()) != null) { resultStr.append(line); } System.out.println(resultStr.toString()); ResultVo resultVo = JSON.parseObject(resultStr.toString(), ResultVo.class); return resultVo; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 測試方法. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 密碼 String password = ""; // 金鑰庫 String keyStorePath = ""; // 信任庫 String trustStorePath = ""; // 本地起的https服務 String httpsUrl = ""; // 傳輸文字 String xmlStr = ""; HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath); // 發起請求 HttpsPost.post(httpsUrl, xmlStr); } }
jar 包 fastjson-1.1.27.jar 、log4j-1.2.11.jar
連結:https://pan.baidu.com/s/1UAGUmc7PhUT0Db65YuQMiA
提取碼:s70w