首先感谢(即不能使用System.setProperty("https.protocols","TLSv1"); )
以下是两个https信任所有证书的实例:
lotnet.util;import java.io.InputStream;
import java.io.OutputStream;
import java.URL;
import java.util.List;import javax.ssl.HttpsURLConnection;
import javax.ssl.SSLContext;
import javax.ssl.SSLSocketFactory;
import javax.ssl.TrustManager;import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ssage.BasicNameValuePair;
import org.apache.http.util.EntityUtils;public class HttpUtil {public static String send(String url, List<BasicNameValuePair> nvps, String ecoding) throws Exception{String respStr = null;DefaultHttpClient httpClient = new SSLClient();HttpPost postMethod = new HttpPost(url);postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));try{HttpResponse resp = ute(postMethod);int statusCode = StatusLine().getStatusCode();if(statusCode == HttpStatus.SC_OK){respStr = Entity(), "UTF-8");}}catch(Exception e){ throw e;}leaseConnection();}return respStr;}public static InputStream post(String submitUrl, String reqData, int connectTimeOut, int readTimeOut, String encoding) throws Exception {
// String path = "E:/Bill99QuickPay/81231015722198890.jks";
// File certFile = new File(path);
// KeyStore ks = Instance("JKS");
// String password = "vpos123";
// ks.load(new FileInputStream(certFile), CharArray());
// KeyManagerFactory kmf = DefaultAlgorithm());
// kmf.init(ks, CharArray());TrustManager[] tm = { new MyX509TrustManager() };
// SSLContext sslContext = Instance("TLSv1");
// System.setProperty("https.protocols","TLSv1"); String protocol = Protocol();System.out.println(protocol);
// sslContext.KeyManagers(),tm, null);sslContext.init(null, tm, new java.security.SecureRandom());SSLSocketFactory factory = SocketFactory();SSLSocketFactoryWrapper wrapper = new SSLSocketFactoryWrapper(factory, new String[] { "TLSv1" }, null);URL url = new URL(submitUrl);HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();urlc.setSSLSocketFactory(wrapper);urlc.setHostnameVerifier(new TrustAnyHostnameVerifier());urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setReadTimeout(readTimeOut);urlc.setConnectTimeout(connectTimeOut);OutputStream out = OutputStream();out.Bytes(encoding));out.flush(); out.close();InputStream();
}// public static String send(String url, String param,int readTimeout, int connTimeOut, String readecoding,String txtType, String sendecoding) throws Exception{
// String respStr = null;
// HttpClient httpClient = new HttpClient();
// PostMethod postmethod = new PostMethod(url);
// // 链接超时
// HttpConnectionManager().getParams().setConnectionTimeout(connTimeOut);
// // 读取超时
// HttpConnectionManager().getParams().setSoTimeout(readTimeout);
// try{
// postmethod.setRequestEntity(new StringRequestEntity(param, txtType,sendecoding));
// int statusCode = uteMethod(postmethod);
// if (statusCode == HttpStatus.SC_OK) {
// BufferedInputStream bis = new ResponseBodyAsStream());
// byte[] bytes = new byte[1024];
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// int count = 0;
// while ((count = ad(bytes)) != -1) {
// bos.write(bytes, 0, count);
// }
// byte[] strByte = ByteArray();
// respStr = new String(strByte, 0, strByte.length, readecoding);
// }
// }catch(Exception e){
// throw e;
// }finally{
// leaseConnection();
// }
// return respStr;
// }}
lotnet.util;import CertificateException;
import X509Certificate;import javax.ssl.SSLContext;
import javax.ssl.TrustManager;
import javax.ssl.X509TrustManager;import org.ClientConnectionManager;
import org.scheme.Scheme;
import org.scheme.SchemeRegistry;
import org.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;public class SSLClient extends DefaultHttpClient {public SSLClient() throws Exception {super();SSLContext ctx = Instance("TLSv1");X509TrustManager tm = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}};ctx.init(null, new TrustManager[] { tm }, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = ConnectionManager();SchemeRegistry sr = SchemeRegistry();sr.register(new Scheme("https", 443, ssf));}
}
lotnet.util;import CertificateException;
import X509Certificate; import javax.ssl.X509TrustManager; public class MyX509TrustManager implements X509TrustManager { public MyX509TrustManager() throws Exception { } /* * Delegate to the default trust manager. */ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } /* * Delegate to the default trust manager. */ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } /* * Merely pass this through. */ public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
}
lotnet.util;import javax.ssl.HostnameVerifier;
import javax.ssl.SSLSession;public class TrustAnyHostnameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}}
lotnet.util;import java.io.IOException;
import java.InetAddress;
import java.Socket;
import java.UnknownHostException;import javax.ssl.SSLSocket;
import javax.ssl.SSLSocketFactory;public class SSLSocketFactoryWrapper extends SSLSocketFactory {private final SSLSocketFactory wrappedFactory;private final String[] enabledProtocols;private final String[] enabledSuites;public SSLSocketFactoryWrapper(SSLSocketFactory factory, String[] protocols, String[] suites) {wrappedFactory = factory;enabledProtocols = protocols;enabledSuites = suites;}/*** @param host* @param port* @return* @throws IOException* @throws UnknownHostException* @see javax.SocketFactory#createSocket(java.lang.String, int)*/public Socket createSocket(String host, int port) throws IOException, UnknownHostException {SSLSocket socket = (ateSocket(host, port);setParameters(socket);return socket;}/*** @param host* @param port* @param localHost* @param localPort* @return* @throws IOException* @throws UnknownHostException* @see javax.SocketFactory#createSocket(java.lang.String, int, java.InetAddress, int)*/public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException,UnknownHostException {SSLSocket socket = (ateSocket(host, port, localHost, localPort);setParameters(socket);return socket;}/*** @param host* @param port* @return* @throws IOException* @see javax.SocketFactory#createSocket(java.InetAddress, int)*/public Socket createSocket(InetAddress host, int port) throws IOException {SSLSocket socket = (ateSocket(host, port);setParameters(socket);return socket;}/*** @param address* @param port* @param localAddress* @param localPort* @return* @throws IOException* @see javax.SocketFactory#createSocket(java.InetAddress, int, java.InetAddress, int)*/public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)throws IOException {SSLSocket socket = (ateSocket(address, port, localAddress, localPort);setParameters(socket);return socket;}/*** @return* @throws IOException* @see javax.SocketFactory#createSocket()*/public Socket createSocket() throws IOException {SSLSocket socket = (ateSocket();setParameters(socket);return socket;}/*** @return* @see javax.ssl.SSLSocketFactory#getDefaultCipherSuites()*/public String[] getDefaultCipherSuites() {DefaultCipherSuites();}/*** @return* @see javax.ssl.SSLSocketFactory#getSupportedCipherSuites()*/public String[] getSupportedCipherSuites() {return enabledSuites == null ? SupportedCipherSuites() : enabledSuites;}/*** @param s* @param host* @param port* @param autoClose* @return* @throws IOException* @see javax.ssl.SSLSocketFactory#createSocket(java.Socket, java.lang.String, int, boolean)*/public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {SSLSocket socket = (ateSocket(s, host, port, autoClose);setParameters(socket);return socket;}/*** Override the configured parameters on the socket.** @param socket*/private void setParameters(SSLSocket socket) {if (enabledProtocols != null) {socket.setEnabledProtocols(enabledProtocols);}if (enabledSuites != null) {socket.setEnabledCipherSuites(enabledSuites);}}
}
注意的是SSLClient中信任所有证书的方式对jdk6不适用,HTTPUtil中的第二个方法可以用于jdk6,需指定System.setProperty("https.protocols","TLSv1"); 如果由于环境问题不能使用System,(System针对整个环境所有的https设置),可使用SSLSocketFactory的包装类 SSLSocketFactoryWrapper来指定一条http连接使用的协议。
本文发布于:2024-02-02 11:17:01,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170684382243435.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |