1.这2天项目中需要调用外部接口,开始以为挺简单的,后面使用HttpConnection发送post请求出现了以下的错误信息.通过观察日志中的错误信息发现,应该是在创建HttpConnection的http连接的时候,出现了SSL安全认证的问题,通过查找相关的资料发现,应该是由于外部接口的https证书中的主机名称与本地https请求的主机名称不一致导致的, 同时通过浏览器访问,发现该地址访问不安全,应该是服务端的证为个人认证导致的。
jodd.http.HttpException: java.security.cert.CertificateException: No name matching nyq.esgcc.com.cn found; <--- java.security.cert.CertificateException: No name matching nyq.esgcc.com.cn found
at jodd.http.net.SocketHttpConnectionProvider.createHttpConnection(SocketHttpConnectionProvider.java:101) ~[SocketHttpConnectionProvider.class:?]
at jodd.http.HttpRequest.open(HttpRequest.java:737) ~[HttpRequest.class:?]
at jodd.http.HttpRequest.open(HttpRequest.java:721) ~[HttpRequest.class:?]
at jodd.http.HttpRequest._send(HttpRequest.java:819) ~[HttpRequest.class:?]
at jodd.http.HttpRequest.send(HttpRequest.java:814) ~[HttpRequest.class:?]
at com.bxd.core.util.HttpUtil.post(HttpUtil.java:126) ~[HttpUtil.class:?]
at com.bxd.core.util.HttpUtil.post(HttpUtil.java:102) ~[HttpUtil.class:?]
at com.bxd.app.controller.TestController.forward(TestController.java:73) ~[TestController.class:?]
at com.bxd.app.controller.TestController$$FastClassBySpringCGLIB$$a0caf4a6.invoke() ~[TestController.class:?]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[MethodProxy.class:4.3.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) ~[CglibAopProxy$CglibMethodInvocation.class:4.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[ReflectiveMethodInvocation.class:4.3.9.RELEASE]
at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52) ~[MethodBeforeAdviceInterceptor.class:4.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ReflectiveMethodInvocation.class:4.3.9.RELEASE]
at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) ~[AfterReturningAdviceInterceptor.class:4.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ReflectiveMethodInvocation.class:4.3.9.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[ExposeInvocationInterceptor.class:4.3.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ReflectiveMethodInvocation.class:4.3.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) ~[CglibAopProxy$DynamicAdvisedInterceptor.class:4.3.9.RELEASE]
at com.bxd.app.controller.TestController$$EnhancerBySpringCGLIB$$e08ed4b.forward() ~[TestController.class:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_102]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_102]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_102]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_102]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[InvocableHandlerMethod.class:4.3.9.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[InvocableHandlerMethod.class:4.3.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[ServletInvocableHandlerMethod.class:4.3.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[RequestMappingHandlerAdapter.class:4.3.9.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[RequestMappingHandlerAdapter.class:4.3.9.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[AbstractHandlerMethodAdapter.class:4.3.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) [DispatcherServlet.class:4.3.9.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) [DispatcherServlet.class:4.3.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [FrameworkServlet.class:4.3.9.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) [FrameworkServlet.class:4.3.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:644) [servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [FrameworkServlet.class:4.3.9.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) [servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) [WebStatFilter.class:1.0.29]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:209) [CORSFilter.class:2.6]
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:244) [CORSFilter.class:2.6]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at com.bxd.core.filter.XssFilter.doFilter(XssFilter.java:45) [XssFilter.class:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [CharacterEncodingFilter.class:4.3.9.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [OncePerRequestFilter.class:4.3.9.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.14]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.14]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) [catalina.jar:8.0.14]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [catalina.jar:8.0.14]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.14]
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:676) [catalina.jar:8.0.14]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) [catalina.jar:8.0.14]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.14]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537) [catalina.jar:8.0.14]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) [tomcat-coyote.jar:8.0.14]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) [tomcat-coyote.jar:8.0.14]
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277) [tomcat-coyote.jar:8.0.14]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403) [tomcat-coyote.jar:8.0.14]
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392) [tomcat-coyote.jar:8.0.14]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_102]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:8.0.14]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_102]
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching nyq.esgcc.com.cn found
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[?:1.8.0_102]
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949) ~[?:1.8.0_102]
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302) ~[?:1.8.0_102]
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296) ~[?:1.8.0_102]
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509) ~[?:1.8.0_102]
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216) ~[?:1.8.0_102]
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979) ~[?:1.8.0_102]
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914) ~[?:1.8.0_102]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062) ~[?:1.8.0_102]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[?:1.8.0_102]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[?:1.8.0_102]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[?:1.8.0_102]
at jodd.http.net.SocketHttpSecureConnection.init(SocketHttpSecureConnection.java:43) ~[SocketHttpSecureConnection.class:?]
at jodd.http.net.SocketHttpConnectionProvider.createHttpConnection(SocketHttpConnectionProvider.java:96) ~[SocketHttpConnectionProvider.class:?]
... 73 more
Caused by: java.security.cert.CertificateException: No name matching nyq.esgcc.com.cn found
at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:221) ~[?:1.8.0_102]
2.下面说一下解决方法,首先网上找了下资料,发现找来的没什么用,无意中问下下朋友,找到了一种可行的发送https请求绕过证书检测的方法。下面附上代码,需要的朋友可以试下,调用doget方法即可,代码会判断是否包含https请求,存在则 使用sendSSLPostMethod静态方法,ignoreHostnameVerifier忽略证书hostName(这个应该是关键).这样这样就可以实现绕过hostName与证书主机名 不一致导致出现 无法匹配的问题了。
package bxdweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class HttpTookit {
private static Logger logger = LoggerFactory.getLogger(HttpTookit.class);
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map params){
if(isHttps(url)){
return sendSSLPostMethod(url, params);
}
else{
return doGet(url, params,CHARSET);
}
}
public static String doPost(String url, Map params){
return doPost(url, params,CHARSET);
}
/**
* HTTP Get 获取内容
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url,Map params,String charset){
if(StringUtils.isBlank(url)){
return null;
}
HttpGet httpGet = null;
try {
if(params != null && !params.isEmpty()){
List pairs = new ArrayList(params.size());
for(Map.Entry entry : params.entrySet()){
if(entry.getValue() != null){
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
logger.info("=======HttpTookit 请求url地址: "+url+"==========");
httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
}finally{
if(httpGet != null) httpGet.releaseConnection();
}
}
/**
* HTTP Post 获取内容
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参�?
* @param charset 编码格式
* @return 页面内容
*/
public static String doPost(String url,Map params,String charset){
if(StringUtils.isBlank(url)){
return null;
}
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
List pairs = null;
if(params != null && !params.isEmpty()){
pairs = new ArrayList(params.size());
for(Map.Entry entry : params.entrySet()){
if(entry.getValue() != null){
pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
}
}
}
httpPost = new HttpPost(url);
httpPost.setHeader("serialSeq","1212121");
httpPost.setHeader("verChl","0.0.1");
httpPost.setHeader("sendChl","hzsmk.test");
httpPost.setHeader("sendClient","hellohzsmk");
httpPost.setHeader("sendDev","121aqweq");
if(pairs != null && pairs.size() > 0){
httpPost.setEntity(new UrlEncodedFormEntity(pairs,CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null){
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
} finally{
if(httpPost != null) httpPost.releaseConnection();
}
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @return
* @throws Exception
*/
protected static HttpsURLConnection initHttps(String url, String method,
Map headers) throws Exception {
TrustManager[] tm = {new MyX509TrustManager()};
System.setProperty("https.protocols", "TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
//sslContext.init(null, tm, null);
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 设置域名校验
http.setHostnameVerifier(new TrustAnyHostnameVerifier());
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
/* http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");*/
if (null != headers && !headers.isEmpty()) {
for (Entry entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
try {
http.connect();
} catch (Exception ex) {
logger.info(ex.getMessage());
}
return http;
}
/**
* 功能描述: 构造请求参数
*
* @return 返回类型:
* @throws Exception
*/
public static String initParams(String url, Map params)
throws Exception {
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
}
sb.append(map2Url(params));
return sb.toString();
}
/**
* map构造url
*
* @return 返回类型:
* @throws Exception
*/
public static String map2Url(Map paramToMap)
throws Exception {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Entry entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue().toString();
if (!StringUtils.isEmpty(value)) {
url.append(URLEncoder.encode(value, CHARSET));
}
}
return url.toString();
}
/**
* 检测是否https
*
* @param url
*/
protected static boolean isHttps(String url) {
return url.startsWith("https");
}
/**
* https 域名校验
*
* @param url
* @param params
* @return
*/
public static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// 直接返回true
}
}
public static class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
/**
* 忽视证书HostName
*/
private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
/**
* Ignore Certification
*/
private static TrustManager ignoreCertificationTrustManger = new X509TrustManager(){
private X509Certificate[] certificates;
public void checkClientTrusted(X509Certificate certificates[],
String authType) throws CertificateException {
if (this.certificates == null) {
this.certificates = certificates;
}
}
public void checkServerTrusted(X509Certificate[] ax509certificate,
String s) throws CertificateException {
if (this.certificates == null) {
this.certificates = ax509certificate;
}
}
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
};
public static String sendSSLGetMethod(String urlString) throws Exception{
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
is.close();
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString,String postData) throws Exception{
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type","text/json");
connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
is.close();
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString,Map params){
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(initParams(urlString,params));
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = { ignoreCertificationTrustManger };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type","text/json");
//connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
//connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if(connection.getResponseCode() != 200){
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if(null != is){
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
is = null;
}
if(null != connection){
connection.disconnect();
}
}
return repString;
}
}
感谢网友的资料:参考资料地址