import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
import java.net.SocketTimeoutException;
public class MyHttpUtil {
public static String doPost(HttpPost post) {
CloseableHttpClient httpClient = DyHttpClientUtils.getEnableSSLClient();
try {
return httpClient.execute(post, new BasicResponseHandler());
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String doGet(HttpGet get) {
CloseableHttpClient httpClient = DyHttpClientUtils.getEnableSSLClient();
try {
return httpClient.execute(get, new BasicResponseHandler());
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (ConnectTimeoutException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class DyHttpClientUtils {
public static CloseableHttpClient getEnableSSLClient() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
e.printStackTrace();
}
return HttpClientBuilder.create().build();
}
private static TrustManager truseAllManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
}