原问题:
: : No subject alternative names present
/robert_lizhiqiang/article/details/44060217
解决报错问题:>
static {
//for localhost testing only
(
new (){
public boolean verify(String hostname,
sslSession) {
if (("localhost")) {
return true;
}else if (("118.85.194.45")) {
return true;
}
return false;
}
});
}
/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/
或者[建议上边的]
/questions/19540289/how-to-fix-the-java-security-cert-certificateexception-no-subject-alternative
解决连接https问题
public static String requestHTTPS(String targetUrl, String method, Map<String,String> params) {
try {
("requestHTTPS targetUrl:"+targetUrl+",method:"+method);
(targetUrl);
URL url = new URL(targetUrl);
HttpsURLConnection connection = () url
.openConnection();
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
///questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
//
KeyStore trustStore = (());
FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/"));
try {
// 加载keyStore
(instream, "D#s@a1".toCharArray());
} catch (CertificateException e) {
();
} catch (NoSuchAlgorithmException e) {
();
} finally {
try {
();
} catch (Exception ignore) {
}
}
TrustManagerFactory tmf =
(());
(trustStore);
//
X509TrustManager defaultTrustManager = (X509TrustManager)()[0];
SSLContext ctx = ("TLS");
(null, new TrustManager[] {defaultTrustManager}, null);
SSLSocketFactory sslFactory = ();
(sslFactory);
(true);
(true);
(method);
(false);
(true);
("Content-Type", "application/json");
("Accept", "application/json");
();
if(params!=null){
//POST请求
DataOutputStream out = new DataOutputStream(
());
(buildRequestParams(params,"UTF-8"));
();
();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = ()) != null) {
lines = new String((), "utf-8");
(lines);
}
();
();
("response:"+());
return ();
} catch (MalformedURLException e) {
();
} catch (UnsupportedEncodingException e) {
();
} catch (IOException e) {
();
} catch (KeyStoreException e1) {
();
} catch (NoSuchAlgorithmException e) {
();
} catch (KeyManagementException e) {
();
}
return null;
}
/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
细节修定:
/2009/01/31/urlconnection-and-https
注意中间
X509TrustManager defaultTrustManager = (X509TrustManager)()[0];
的细节问题
全部代码如下:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .X509TrustManager;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class UtilRest {
private static Log log=();
static {
//for localhost testing only
(
new (){
public boolean verify(String hostname,
sslSession) {
if (("localhost")) {
return true;
}else if (("118.85.194.45")) {
return true;
}
return false;
}
});
}
public static void main(String[] args) {
JSONObject response=("https://118.85.194.45:8080/");
}
public static JSONObject get(String targetUrl) {
HttpClient httpClient = new HttpClient();
HttpMethodBase method = new GetMethod();
JSONObject response = null;
try {
(new URI(targetUrl, false));
int statusCode = (method);
if (statusCode != HttpStatus.SC_OK) {
("Method failed: "
+ () + " for url " + targetUrl);
}
String strResponse = ();
response = (strResponse);
return response;
} catch (Exception e) {
("Please check your provided http address!");
} finally {
if (method != null)
();
}
if (response == null)
return null;
return null;
}
public static JSONObject post(String targetUrl) {
return post(targetUrl,null);
}
public static JSONObject post(String targetUrl,Map<String,String> params) {
String result = null;
if (("https")) {
result = requestHTTPS(targetUrl, "POST",params);
}else if (("http")) {
result = request(targetUrl, "POST",params);
}
if (result != null)
try {
return (result);
} catch (Exception e) {
}
return null;
}
public static JSONObject put(String targetUrl) {
String result = request(targetUrl, "PUT",null);
if (result != null)
try {
return (result);
} catch (Exception e) {
}
return null;
}
public static JSONObject delete(String targetUrl) {
String result = request(targetUrl, "DELETE",null);
if (result != null)
try {
return (result);
} catch (Exception e) {
}
return null;
}
public static String request(String targetUrl, String method, Map<String,String> params) {
try {
("request targetUrl:"+targetUrl+",method:"+method);
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
(true);
(true);
(method);
(false);
(true);
("Content-Type", "application/json");
("Accept", "application/json");
();
if(params!=null){
//POST请求
DataOutputStream out = new DataOutputStream(
());
(buildRequestParams(params,"UTF-8"));
();
();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = ()) != null) {
lines = new String((), "utf-8");
(lines);
}
();
();
("response:"+());
return ();
} catch (MalformedURLException e) {
();
} catch (UnsupportedEncodingException e) {
();
} catch (IOException e) {
();
}
return null;
}
public static String requestHTTPS(String targetUrl, String method, Map<String,String> params) {
try {
("requestHTTPS targetUrl:"+targetUrl+",method:"+method);
(targetUrl);
URL url = new URL(targetUrl);
HttpsURLConnection connection = () url
.openConnection();
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
///questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection
//
KeyStore trustStore = (());
FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/"));
try {
// 加载keyStore
(instream, "D#s@a1".toCharArray());
} catch (CertificateException e) {
();
} catch (NoSuchAlgorithmException e) {
();
} finally {
try {
();
} catch (Exception ignore) {
}
}
TrustManagerFactory tmf =
(());
(trustStore);
//
X509TrustManager defaultTrustManager = (X509TrustManager)()[0];
SSLContext ctx = ("TLS");
(null, new TrustManager[] {defaultTrustManager}, null);
SSLSocketFactory sslFactory = ();
(sslFactory);
(true);
(true);
(method);
(false);
(true);
("Content-Type", "application/json");
("Accept", "application/json");
();
if(params!=null){
//POST请求
DataOutputStream out = new DataOutputStream(
());
(buildRequestParams(params,"UTF-8"));
();
();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = ()) != null) {
lines = new String((), "utf-8");
(lines);
}
();
();
("response:"+());
return ();
} catch (MalformedURLException e) {
();
} catch (UnsupportedEncodingException e) {
();
} catch (IOException e) {
();
} catch (KeyStoreException e1) {
();
} catch (NoSuchAlgorithmException e) {
();
} catch (KeyManagementException e) {
();
}
return null;
}
public static String buildRequestParams(Map<String, String> params,
String charset) throws UnsupportedEncodingException {
if (params == null || ()) {
return null;
}
// 对参数进行排序
List<<String, String>> newParams = new ArrayList<<String, String>>(
());
(newParams,
new Comparator<<String, String>>() {
public int compare(<String, String> o1,
<String, String> o2) {
return (()).toString().compareTo(());
}
});
StringBuilder query = new StringBuilder();
for (<String, String> entry : newParams) {
String name = ();
String value = ();
("&");
(name).append("=").append((value, charset));
}
if(!"".equalsIgnoreCase(()))
return ().substring(1, ().length());
return ();
}
}
使用httpclient组件的方式:
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class HttpClientTest {
public static void main(String[] args) {
HttpClientTest client = new HttpClientTest();
();
}
/**
* HttpClient连接SSL
*/
public void ssl() {
CloseableHttpClient httpclient = null;
try {
KeyStore trustStore = (());
FileInputStream instream = new FileInputStream(new File("/Users/yol/Documents/"));
try {
// 加载keyStore d:\\
(instream, "D#s@a1".toCharArray());
} catch (CertificateException e) {
();
} finally {
try {
();
} catch (Exception ignore) {
}
}
// 相信自己的CA和所有自签名的证书
SSLContext sslcontext = ().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
// 只允许使用TLSv1协议
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = ().setSSLSocketFactory(sslsf).build();
// 创建http请求(get方式)
HttpPost httpget = new HttpPost("https://118.85.194.45:8080");
("executing request" + ());
CloseableHttpResponse response = (httpget);
try {
HttpEntity entity = ();
("----------------------------------------");
(());
if (entity != null) {
("Response content length: " + ());
((entity));
(entity);
}
} finally {
();
}
} catch (ParseException e) {
();
} catch (IOException e) {
();
} catch (KeyManagementException e) {
();
} catch (NoSuchAlgorithmException e) {
();
} catch (KeyStoreException e) {
();
} finally {
if (httpclient != null) {
try {
();
} catch (IOException e) {
();
}
}
}
}
/**
* post方式提交表单(模拟用户登录请求)
*/
public void postForm() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = ();
// 创建httppost
HttpPost httppost = new HttpPost("https://118.85.194.45:9001/ucid/app/login");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
(new BasicNameValuePair("user", "monitor"));
(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
(uefEntity);
("executing request " + ());
CloseableHttpResponse response = (httppost);
try {
HttpEntity entity = ();
if (entity != null) {
("--------------------------------------");
("Response content: " + (entity, "UTF-8"));
("--------------------------------------");
}
} finally {
();
}
} catch (ClientProtocolException e) {
();
} catch (UnsupportedEncodingException e1) {
();
} catch (IOException e) {
();
} finally {
// 关闭连接,释放资源
try {
();
} catch (IOException e) {
();
}
}
}
/**
* 发送 post请求访问本地应用并根据传递参数不同返回不同结果
*/
public void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = ();
// 创建httppost
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/");
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
(new BasicNameValuePair("type", "house"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
(uefEntity);
("executing request " + ());
CloseableHttpResponse response = (httppost);
try {
HttpEntity entity = ();
if (entity != null) {
("--------------------------------------");
("Response content: " + (entity, "UTF-8"));
("--------------------------------------");
}
} finally {
();
}
} catch (ClientProtocolException e) {
();
} catch (UnsupportedEncodingException e1) {
();
} catch (IOException e) {
();
} finally {
// 关闭连接,释放资源
try {
();
} catch (IOException e) {
();
}
}
}
/**
* 发送 get请求
*/
public void get() {
CloseableHttpClient httpclient = ();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("https://118.85.194.45:8080");
("executing request " + ());
// 执行get请求.
CloseableHttpResponse response = (httpget);
try {
// 获取响应实体
HttpEntity entity = ();
("--------------------------------------");
// 打印响应状态
(());
if (entity != null) {
// 打印响应内容长度
("Response content length: " + ());
// 打印响应内容
("Response content: " + (entity));
}
("------------------------------------");
} finally {
();
}
} catch (ClientProtocolException e) {
();
} catch (ParseException e) {
();
} catch (IOException e) {
();
} finally {
// 关闭连接,释放资源
try {
();
} catch (IOException e) {
();
}
}
}
/**
* 上传文件
*/
public void upload() {
CloseableHttpClient httpclient = ();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/");
FileBody bin = new FileBody(new File("F:\\image\\"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = ().addPart("bin", bin).addPart("comment", comment).build();
(reqEntity);
("executing request " + ());
CloseableHttpResponse response = (httppost);
try {
("----------------------------------------");
(());
HttpEntity resEntity = ();
if (resEntity != null) {
("Response content length: " + ());
}
(resEntity);
} finally {
();
}
} catch (ClientProtocolException e) {
();
} catch (IOException e) {
();
} finally {
try {
();
} catch (IOException e) {
();
}
}
}
}
//</namevaluepair></namevaluepair></namevaluepair></namevaluepair>