Https與Http類似,只不過Https一般是通過post請求伺服器,但是Https與http不同的是Https與伺服器會話是處於串連狀態。http則發送請求後串連就會斷開。
發送post請求代碼:
String query = r4 + "&pass=" + r3; //請求參數
byte[] entitydata = query.getBytes();//得到實體資料
HttpsURLConnection urlCon = (new URL(ticketurl)).openConnection();
urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
urlCon.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
((HttpsURLConnection) urlCon).setRequestMethod("POST");
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.connect();
//把封裝好的實體資料發送到輸出資料流
OutputStream outStream = urlCon.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
//伺服器返回輸入資料流並讀寫
BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
return line;
}
in.close();
另外使用HttpsURLConnection時需要實現HostnameVerifier 和 X509TrustManager,這兩個實現是必須的,要不會報安全驗證異常。然後初始化X509TrustManager中的SSLContext,為javax.net.ssl.HttpsURLConnection設定預設的SocketFactory和HostnameVerifier。代碼如下:
private myX509TrustManager xtm = new myX509TrustManager();
private myHostnameVerifier hnv = new myHostnameVerifier();
public HttpsURLConnectionTest() {
//初始化X509TrustManager中的SSLContext
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
sslContext.init(null, xtmArray, new java.security.SecureRandom());
} catch (GeneralSecurityException gse) {
}
//為javax.net.ssl.HttpsURLConnection設定預設的SocketFactory和HostnameVerifier
if (sslContext != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
HttpsURLConnection.setDefaultHostnameVerifier(hnv);
這樣就不會報錯了。