出现这个报错是因为客户端发起的http请求缺少证书,如果服务端提供了证书,客户端按照服务端的要求安装证书即可,如果没有证书咋们可以使用apache提供方法进行绕过ssl认证达到正常的请求。下面咋们拿代码举例说明。
public static String doGet() {
String uriAPI = "https://127.0.0.1:4430/demo";
String result = "";
HttpGet httpRequst = new HttpGet(uriAPI);
try { //普通的请求方式
// CloseableHttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
CloseableHttpClient closeableHttpClient = doGetH.getcloseableHttpClient();
//使用DefaultHttpClient类的execute方法发送HTTP GET请求,并返回HttpResponse对象。 绕过SSL方式
HttpResponse httpResponse = closeableHttpClient.execute(httpRequst);//其中HttpGet是HttpUriRequst的子类
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);//取出应答字符串
// 一般来说都要删除多余的字符
result.replaceAll("\r", "");//去掉返回结果中的"\r"字符,否则会在结果字符串后面显示一个小方格
} else
httpRequst.abort();
} catch (ClientProtocolException e) {
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
//绕过SSL认证
public static CloseableHttpClient getcloseableHttpClient() {
try {
SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
return HttpClients.custom().setSSLSocketFactory(factory).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}