1. 程式人生 > >Java的post(HTTPS)請求-----接口測試

Java的post(HTTPS)請求-----接口測試

eat class tin hostname ted buffered lin hat tls

這個是忽略證書的辦法

  1 package com.ju.util;
  2 
  3 
  4 import java.io.BufferedReader;
  5 import java.io.IOException;
  6 
  7 import java.io.InputStreamReader;
  8 import java.io.OutputStream;
  9 import java.io.OutputStreamWriter;
 10 import java.io.PrintWriter;
 11 import java.net.HttpURLConnection;
 12
import java.net.URL; 13 import java.util.Map; 21 import javax.net.ssl.HostnameVerifier; 22 import javax.net.ssl.HttpsURLConnection; 23 import javax.net.ssl.SSLContext; 24 import javax.net.ssl.SSLSession; 25 import javax.net.ssl.TrustManager; 32 import net.sf.json.JSONObject; 34 import java.security.cert.X509Certificate;
36 import javax.net.ssl.X509TrustManager; public class HttpPost { 41 42 43 private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { 44 public boolean verify(String hostname, SSLSession session) { 45 return true; 46 } 47 };
48 49 private static void trustAllHosts() { 50 // Create a trust manager that does not validate certificate chains 51 TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { 52 public java.security.cert.X509Certificate[] getAcceptedIssuers() { 53 return new java.security.cert.X509Certificate[]{}; 54 } 55 56 public void checkClientTrusted(X509Certificate[] chain, String authType) { 57 } 58 59 public void checkServerTrusted(X509Certificate[] chain, String authType) { 60 } 61 }}; 62 // Install the all-trusting trust manager 63 try { 64 SSLContext sc = SSLContext.getInstance("TLS"); 65 sc.init(null, trustAllCerts, new java.security.SecureRandom()); 66 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 67 } catch (Exception e) { 68 e.printStackTrace(); 69 } 70 } 71 72 public static String https(String url, Map<String, String> params) throws Exception { 73 // 構建請求參數 74 String result = ""; 75 PrintWriter out = null; 76 BufferedReader in = null; 77 78 String sendString = ""; 79 JSONObject json = JSONObject.fromObject(params); 80 System.out.println("發送報文:" + json.toString()); 81 sendString = json.toString(); 82 83 System.out.println("ERP連接:" + url); 84 System.out.println("發送給ERP信息:" + sendString); 85 86 try { 87 trustAllHosts(); 88 URL url2 = new URL(url); 89 90 HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection(); 91 urlCon.setHostnameVerifier(DO_NOT_VERIFY); 92 urlCon.setDoOutput(true); 93 urlCon.setDoInput(true); 94 urlCon.setRequestMethod("POST"); 95 urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8"); 96 // 發送POST請求必須設置如下兩行 97 urlCon.setDoOutput(true); 98 urlCon.setDoInput(true); 99 // 獲取URLConnection對象對應的輸出流 100 OutputStream os = urlCon.getOutputStream(); 101 //參數是鍵值隊 , 不以"?"開始 102 os.write(sendString.getBytes()); 103 //os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes()); 104 os.flush(); 105 // 發送請求參數 106 //out.print(a); 107 // flush輸出流的緩沖 108 //out.flush(); 109 // 定義BufferedReader輸入流來讀取URL的響應 110 in = new BufferedReader( 111 new InputStreamReader(urlCon.getInputStream())); 112 String line; 113 while ((line = in.readLine()) != null) { 114 result += line; 115 } 116 } catch (Exception e) { 117 e.printStackTrace(); 118 } finally {// 使用finally塊來關閉輸出流、輸入流 119 try { 120 if (out != null) { 121 out.close(); 122 } 123 if (in != null) { 124 in.close(); 125 } 126 } catch (IOException ex) { 127 ex.printStackTrace(); 128 } 129 } 130 return result; 131 } 132 133 public static String http(String url, Map<String, String> reqMap) throws Exception { 134 135 URL u = null; 136 137 HttpURLConnection con = null; 138 139 // 構建請求參數 140 141 //StringBuffer sb = new StringBuffer(); 142 String sendString = "" ; 143 //String tradeCode = params.get(ParamsConfig.keyTradeCode); 144 JSONObject json = JSONObject.fromObject(reqMap); 145 System.out.println("發送報文:"+json.toString()); 146 sendString = json.toString(); 147 /*if(tradeCode.equals(TradeCode.TRANS_WXAPP_PAY) || tradeCode.equals(TradeCode.TRANS_APP_QUERY) 148 || tradeCode.equals(TradeCode.TRANS_TYPE_COLLECT) || tradeCode.equals(TradeCode.TRANS_TYPE_QUERY_COLLECT_TXN)){ 149 JSONObject json = JSONObject.fromObject(params); 150 System.out.println("發送報文:"+json.toString()); 151 sendString = json.toString(); 152 } else { 153 if (params != null) { 154 155 for (Entry<String, String> e : params.entrySet()) { 156 157 sb.append(e.getKey()); 158 159 sb.append("="); 160 161 sb.append(e.getValue()); 162 163 sb.append("&"); 164 165 } 166 sendString = sb.substring(0, sb.length() - 1); 167 } 168 }*/ 169 System.out.println("ERP連接:" + url); 170 System.out.println("發送給ERP信息:" + sendString); 171 // logger.info("ERP連接:" + url); 172 // logger.info("發送給ERP信息:" + sb.toString()); 173 174 // 嘗試發送請求 175 176 try { 177 178 u = new URL(url); 179 180 con = (HttpURLConnection) u.openConnection(); 181 182 con.setRequestMethod("POST"); 183 184 con.setDoOutput(true); 185 186 con.setDoInput(true); 187 188 con.setUseCaches(false); 189 190 // con.setConnectTimeout(300*1000); 191 // 192 // con.setReadTimeout(300*1000); 193 194 con.setRequestProperty("Content-Type", 195 "application/x-www-form-urlencoded"); 196 197 OutputStreamWriter osw = new OutputStreamWriter(con 198 .getOutputStream(), "UTF-8"); 199 200 osw.write(sendString); 201 202 osw.flush(); 203 204 osw.close(); 205 206 } catch (Exception e) { 207 e.printStackTrace(); 208 throw new Exception("與服務器連接發生錯誤:"+e.getMessage()); 209 210 } finally { 211 212 if (con != null) { 213 214 con.disconnect(); 215 216 } 217 218 } 219 220 // 讀取返回內容 221 222 StringBuffer buffer = new StringBuffer(); 223 224 try { 225 226 BufferedReader br = new BufferedReader(new InputStreamReader(con 227 228 .getInputStream(), "UTF-8")); 229 230 String temp; 231 232 while ((temp = br.readLine()) != null) { 233 234 buffer.append(temp); 235 } 236 237 } catch (Exception e) { 238 e.printStackTrace(); 239 throw new Exception("從服務器獲取數據失敗:"+e.getMessage()); 240 241 } 242 243 return buffer.toString(); 244 245 } 246 247 248 249 }

Java的post(HTTPS)請求-----接口測試