Skip to content

Instantly share code, notes, and snippets.

@SuelenGC
Created April 15, 2014 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SuelenGC/10788937 to your computer and use it in GitHub Desktop.
Save SuelenGC/10788937 to your computer and use it in GitHub Desktop.
Doing https request with unknown certificate
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
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 WebClient {
private final String url;
public WebClient(String url) {
this.url = url;
}
public String postHttps() {
String res = "";
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("usp_id", "usp number"));
params.add(new BasicNameValuePair("password", "stoa password"));
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
}, null);
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(this.url);
request.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(request);
res = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment