import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
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;
public class Main {
public static void main(String[] args) throws Exception {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(
X509Certificate[] x509Certificates,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
HostnameVerifier dummyHostnameVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(dummyHostnameVerifier);
String host = "https://host";
String parameterName = "parameter";
String parameterValue = "value";
URL url = new URL(host);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
try {
os.write((parameterName + "=" + URLEncoder.encode(parameterValue,
"UTF-8")).getBytes());
} finally {
os.close();
}
StringWriter sw = new StringWriter();
InputStream in = conn.getInputStream();
try {
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
sw.write(s + "\n");
s = br.readLine();
}
} finally {
in.close();
sw.close();
}
System.out.println(sw.toString());
}
}
2008年12月7日
HttpsURLConnection bypass the CertificateExpiredException
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言