JAVA實現HTTPS協議POST請求JSON報文
阿新 • • 發佈:2019-01-05
package https;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class PostJson {
private static class TrustAnyTrustManager implements X509TrustManager {
//該方法檢查客戶端的證書,若不信任該證書則丟擲異常。由於我們不需要對客戶端進行認證,因此我們只需要執行預設的信任管理器的這個方法。
//JSSE中,預設的信任管理器類為TrustManager。
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
//該方法檢查伺服器的證書,若不信任該證書同樣丟擲異常。通過自己實現該方法,可以使之信任我們指定的任何證書。在實現該方法時,也可以簡單的不做任何處理,即一個空的函式體,由於不會丟擲異常,它就會信任任何證書。
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
//返回受信任的X509證書陣列。
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* post方式請求伺服器(https協議)
*
* @param url
* 請求地址
* @param content
* 引數
* @param charset
* 編碼
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static byte[] post(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException,
IOException {
/*類HttpsURLConnection似乎並沒有提供方法設定信任管理器。其實,HttpsURLConnection通過SSLSocket來建立與HTTPS的安全連線,SSLSocket物件是由SSLSocketFactory生成的。
* HttpsURLConnection提供了方法setSSLSocketFactory(SSLSocketFactory)設定它使用的SSLSocketFactory物件。
* SSLSocketFactory通過SSLContext物件來獲得,在初始化SSLContext物件時,可指定信任管理器物件。
* */
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.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
//設定請求頭
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// 重新整理、關閉
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException{
String url = "https://xxx.xxx.xxx/path/to/dir/${action}";
PostJson pj = new PostJson();
String content=pj.getbaowen();
String charset="UTF-8";
byte[] a = pj.post(url, content, charset);
String b = new String(a);
System.out.println(b);
}
//構造巢狀的JSON報文方式,即在new一個JSONObject,並返回報文字串
public String getbaowen(){
JSONObject test= new JSONObject();
test.put("xxxx", "");
String resp= null;
JSONObject obj = new JSONObject();
obj.put("xxxxxx", "");
obj.put("test", test);
String query = obj.toString();
return query;
}
}
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class PostJson {
private static class TrustAnyTrustManager implements X509TrustManager {
//該方法檢查客戶端的證書,若不信任該證書則丟擲異常。由於我們不需要對客戶端進行認證,因此我們只需要執行預設的信任管理器的這個方法。
//JSSE中,預設的信任管理器類為TrustManager。
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
//該方法檢查伺服器的證書,若不信任該證書同樣丟擲異常。通過自己實現該方法,可以使之信任我們指定的任何證書。在實現該方法時,也可以簡單的不做任何處理,即一個空的函式體,由於不會丟擲異常,它就會信任任何證書。
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
//返回受信任的X509證書陣列。
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
/**
* post方式請求伺服器(https協議)
*
* @param url
* 請求地址
* @param content
* 引數
* @param charset
* 編碼
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static byte[] post(String url, String content, String charset)
throws NoSuchAlgorithmException, KeyManagementException,
IOException {
/*類HttpsURLConnection似乎並沒有提供方法設定信任管理器。其實,HttpsURLConnection通過SSLSocket來建立與HTTPS的安全連線,SSLSocket物件是由SSLSocketFactory生成的。
* HttpsURLConnection提供了方法setSSLSocketFactory(SSLSocketFactory)設定它使用的SSLSocketFactory物件。
* SSLSocketFactory通過SSLContext物件來獲得,在初始化SSLContext物件時,可指定信任管理器物件。
* */
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.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
//設定請求頭
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// 重新整理、關閉
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException{
String url = "https://xxx.xxx.xxx/path/to/dir/${action}";
PostJson pj = new PostJson();
String content=pj.getbaowen();
String charset="UTF-8";
byte[] a = pj.post(url, content, charset);
String b = new String(a);
System.out.println(b);
}
//構造巢狀的JSON報文方式,即在new一個JSONObject,並返回報文字串
public String getbaowen(){
JSONObject test= new JSONObject();
test.put("xxxx", "");
String resp= null;
JSONObject obj = new JSONObject();
obj.put("xxxxxx", "");
obj.put("test", test);
String query = obj.toString();
return query;
}
}