直接上代碼,可用
第一個類:
package com.yili.test.http;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SslUtil {
private static void trustAllHttpsCertificates() throws Exception {?
? ? TrustManager[] trustAllCerts = new TrustManager[1];?
? ? TrustManager tm = new miTM();?
? ? trustAllCerts[0] = tm;?
? ? SSLContext sc = SSLContext.getInstance("SSL");?
? ? sc.init(null, trustAllCerts, null);?
? ? HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());?
}?
static class miTM implements TrustManager,X509TrustManager {?
? ? public X509Certificate[] getAcceptedIssuers() {?
? ? ? ? return null;?
? ? }?
? ? public boolean isServerTrusted(X509Certificate[] certs) {?
? ? ? ? return true;?
? ? }?
? ? public boolean isClientTrusted(X509Certificate[] certs) {?
? ? ? ? return true;?
? ? }?
? ? public void checkServerTrusted(X509Certificate[] certs, String authType)?
? ? ? ? ? ? throws CertificateException {?
? ? ? ? return;?
? ? }?
? ? public void checkClientTrusted(X509Certificate[] certs, String authType)?
? ? ? ? ? ? throws CertificateException {?
? ? ? ? return;?
? ? }?
}?
/**
* 忽略HTTPS請求的SSL證書,必須在openConnection之前調(diào)用
* @throws Exception
*/?
public static void ignoreSsl() throws Exception{?
? ? HostnameVerifier hv = new HostnameVerifier() {?
? ? ? ? public boolean verify(String urlHostName, SSLSession session) {?
? ? ? ? ? ? System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());?
? ? ? ? ? ? return true;?
? ? ? ? }?
? ? };?
? ? trustAllHttpsCertificates();?
? ? HttpsURLConnection.setDefaultHostnameVerifier(hv);?
}?
}
第二個類:
package com.yili.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.params.HttpMethodParams;
import com.yili.test.http.SslUtil;
public abstract class EM3 {
public static void main(String[] args) throws Exception {
String basePushUrl = "https://XX.XX.XX.XX/pushMessage.do";//接口地址
try {
try {
HttpClient httpClient = new HttpClient();
//設(shè)置訪問編碼
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//讓服務(wù)器知道訪問源為瀏覽器
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1");
Map<String, String> parameters=new HashMap<String, String> ();//接口參數(shù)
parameters.put("userid", "0034523");
System.out.println(post(basePushUrl,parameters));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String post(String path,Map<String, String> parameters) throws Exception{
// 創(chuàng)建SSLContext對象,并使用我們指定的信任管理器初始化
? ? TrustManager[] tm = { new MyX509TrustManager() };
? ? SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
//? ? SSLContext sc = SSLContext.getInstance("TLS");
// sc.init(null, trustAllCerts, new SecureRandom());
? ? sslContext.init(null, tm, new java.security.SecureRandom());
? ? // 從上述SSLContext對象中得到SSLSocketFactory對象
? ? SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(path);
if (parameters != null) {
url = new URL(url.toString() + buildGetParameterString(parameters));
System.out.println("url:"+url.toString() );
}
SslUtil? ssu=new? SslUtil();
ssu.ignoreSsl();
HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
httpsConn.setRequestMethod("POST");
? ? httpsConn.setSSLSocketFactory(ssf);
? ? httpsConn.setDoInput(true);// 打開輸入流,以便從服務(wù)器獲取數(shù)據(jù)
? ? httpsConn.setDoOutput(true);// 打開輸出流,以便向服務(wù)器提交數(shù)據(jù)
? ? httpsConn.setUseCaches(false);
? ? httpsConn.setInstanceFollowRedirects(true);
? ? httpsConn.addRequestProperty("Content-Type","application/json");
? ? httpsConn.addRequestProperty("Authorization","Basic RG9jdG9yWDoyMjIyMjI=");
? ? httpsConn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(?
? ? ? ? httpsConn.getInputStream()));?
? ? ? ? String line;?
? ? ? ? StringBuffer rt = new StringBuffer();
? ? ? ? while ((line = in.readLine()) != null) {?
? ? ? ? ? ? rt.append(line);?
? ? ? ? }?
return rt.toString();
}
private static String buildGetParameterString(Map<String, String> parameters)
{
String getParameterString = "";
for(Map.Entry<String, String> param : parameters.entrySet())
{
if(param.getValue() == null)
{
continue;
}
getParameterString += (getParameterString.length() < 1) ? ("?") : ("&");
getParameterString += param.getKey() + "=" + param.getValue();
}
return (getParameterString);
}
}
用到的jar包
apache-commons-codec-1.4.jar
commons-codec-1.13.jar
commons-httpclient-3.1.jar
commons-logging-1.2.jar
httpclient-osgi-4.5.11.jar
httpcore-4.4.13.jar