最近使用https请求获取数据出现以下错误:
2017-10-12 16:58:10.113 [main] ERROR com.research.contactsrepairing.util.HttpUtil - post请求提交失败:https://10.100.32.150/kg/ir/repair/getRepaired/
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
此时util是沿用的之前http的,没有做更改:
public static JSONObject httpSPost(String url, String jsonParam, boolean noNeedResponse){ //post请求返回结果 HttpClient httpClient = HttpClientBuilder.create().build(); JSONObject jsonResult = null; HttpPost method = new HttpPost(url); try { if (null != jsonParam) { //解决中文乱码问题 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8"); /**请求发送成功,并得到响应**/ if (result.getStatusLine().getStatusCode() == 200) { String str = ""; try { /**读取服务器返回过来的json字符串数据**/ str = EntityUtils.toString(result.getEntity()); if (noNeedResponse) { return null; } /**把json字符串转换成json array对象**/ jsonResult= JSON.parseObject(str); } catch (Exception e) { logger.error("post请求提交失败:" + url, e); } } } catch (IOException e) { logger.error("post请求提交失败:" + url, e); } return jsonResult; }
调用:
HttpUtil request = new HttpUtil(); JSONObject result = request.httpSPost(url, message,false);
错误截图:
原因描述:
这是https请求,所以需要使用https的方式进行请求
我们需要一个httpclient https 的类
package com.research.contactsrepairing.util; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HTTPSSecureProtocolSocketFactory implements ProtocolSocketFactory { private SSLContext sslcontext = null; private SSLContext createSSLContext() { SSLContext sslcontext = null; try { sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return sslcontext; } private SSLContext getSSLContext() { if (null == this.sslcontext) { this.sslcontext = createSSLContext(); } return this.sslcontext; } public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); SocketFactory socketfactory = getSSLContext().getSocketFactory(); if (timeout == 0) { return socketfactory.createSocket(host, port, localAddress, localPort); } else { Socket socket = socketfactory.createSocket(); SocketAddress localaddr = new InetSocketAddress(localAddress, localPort); SocketAddress remoteaddr = new InetSocketAddress(host, port); socket.bind(localaddr); socket.connect(remoteaddr, timeout); return socket; } } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }
封装一个HttpUtils工具类:
package com.research.contactsrepairing.util; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import java.io.IOException; public class HttpsUtils { /** * 通过url链接直接获取String数据 * @param url * @return */ public static String getStringByHttps(String url) { String result = ""; Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443); Protocol.registerProtocol("https", https); GetMethod get = new GetMethod(url); HttpClient client = new HttpClient(); try { client.executeMethod(get); result = get.getResponseBodyAsString(); result = new String(result.getBytes("ISO-8859-1"), "UTF-8"); Protocol.unregisterProtocol("https"); return result; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return "error"; } /** * 通过url链接加参数直接获取String数据 * @param url * @param * @contentType :application/json * @return */ public static String postByHttps(String url, String body, String contentType) { String result = ""; Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443); Protocol.registerProtocol("https", https); PostMethod post = new PostMethod(url); HttpClient client = new HttpClient(); try { post.setRequestHeader("Content-Type", contentType); post.setRequestBody(body); client.executeMethod(post); result = post.getResponseBodyAsString(); Protocol.unregisterProtocol("https"); return result; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } return "error"; } }
使用方式:
String url = "https://localhost/kg/rr/reppp/getRepeee/"; String result =HttpsUtils.postByHttps(url, message,"application/json");