import javax.net.ssl.*;import java.io.*;importjava.net.URL;importjava.security.KeyManagementException;importjava.security.NoSuchAlgorithmException;importjava.security.SecureRandom;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;/*** Https助手*/
public classHttpsUtil {private static final class DefaultTrustManager implements 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;
}
}private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throwsIOException {
SSLContext ctx= null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
SSLSocketFactory ssf=ctx.getSocketFactory();
URL url= newURL(uri);
HttpsURLConnection httpsConn=(HttpsURLConnection) url.openConnection();//绕过HTTPS相关证书关键代码-开始
httpsConn.setSSLSocketFactory(ssf);//绕过HTTPS相关证书关键代码-结束
httpsConn.setHostnameVerifier(newHostnameVerifier() {
@Overridepublic booleanverify(String arg0, SSLSession arg1) {return true;
}
});
httpsConn.setRequestMethod(method);
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);returnhttpsConn;
}private static byte[] getBytesFromStream(InputStream is) throwsIOException {
ByteArrayOutputStream baos= newByteArrayOutputStream();byte[] kb = new byte[1024];intlen;while ((len = is.read(kb)) != -1) {
baos.write(kb,0, len);
}byte[] bytes =baos.toByteArray();
baos.close();
is.close();returnbytes;
}private static void setBytesToStream(OutputStream os, byte[] bytes) throwsIOException {
ByteArrayInputStream bais= newByteArrayInputStream(bytes);byte[] kb = new byte[1024];intlen;while ((len = bais.read(kb)) != -1) {
os.write(kb,0, len);
}
os.flush();
os.close();
bais.close();
}public static byte[] doGet(String uri) throwsIOException {
HttpsURLConnection httpsConn= getHttpsURLConnection(uri, "GET");returngetBytesFromStream(httpsConn.getInputStream());
}public static byte[] doPost(String uri, String data) throwsIOException {
HttpsURLConnection httpsConn= getHttpsURLConnection(uri, "POST");
setBytesToStream(httpsConn.getOutputStream(), data.getBytes());returngetBytesFromStream(httpsConn.getInputStream());
}
}