http请求是我们常用的一种web应用的应用层协议,但是由于它的不安全性,现在正在逐渐向https协议过渡。https协议是在http的基础上进行了隧道加密,加密方式有SSL和TLS两种。当server用https协议进行数据交换后,client请求server时会对server的证书进行校验,如果server端证书为四大证书机构颁发的证书或者其授权机构颁发的证书,则允许进一步请求,否则会警告证书不受信任。更多信息可参考https://www.cnblogs.com/handsomeBoys/p/6556336.html
当用httpclient进行请求https,会提示找不到有效的证书(unable to find valid certification path to requested target)
出现这种情况就是server端的证书不被信任,可以通过重写一个类继承DefaultHttpClient类,代码如下:
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient; 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 SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new 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;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
然后在进行https请求创建HttpClient对象时用这个类的构造器创建对象就可以实现https请求,例如:
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient; public class RestApi { public static String getCsrf(){
String csrfToken = "";
try {
CloseableHttpClient client = new SSLClient();
String url = "https://10.67.19.186";
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
Header setCookidHeader = response.getFirstHeader("Set-Cookie");
csrfToken = setCookidHeader.getValue().split(";")[0].split("=")[1];
} catch (Exception e) {
e.printStackTrace();
}
return csrfToken;
}