java无证书调用https

1.信任所有证书类

package com.asiainfo.frame.utils.https;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class MyAllTrustManager 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[]{};

}

}

2.工厂类

package com.asiainfo.frame.utils.https;

import java.io.IOException;

import java.net.InetAddress;

import java.net.InetSocketAddress;

import java.net.Socket;

import java.net.SocketAddress;

import java.net.UnknownHostException;

import java.util.Hashtable;

import javax.net.SocketFactory;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import org.apache.axis.components.net.BooleanHolder;

import org.apache.axis.components.net.JSSESocketFactory;

import org.apache.commons.httpclient.ConnectTimeoutException;

import org.apache.commons.httpclient.params.HttpConnectionParams;

import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

public class MyProtocolSocketFactory extends JSSESocketFactory implements ProtocolSocketFactory {

@SuppressWarnings("rawtypes")

public MyProtocolSocketFactory(Hashtable attributes) {

super(attributes);

}

private SSLContext sslContext = null;

private SSLContext createSSLContext() {

   SSLContext sslContext = null;

   try {

sslContext = SSLContext.getInstance("SSL", "SunJSSE");

TrustManager[] tm = {new MyAllTrustManager()};

   sslContext.init(null, tm, new java.security.SecureRandom());

} catch (Exception e) {

throw new RuntimeException(e);

}

   return sslContext;

}

private SSLContext getSSLContext() {

   if (this.sslContext == null) {

       this.sslContext = createSSLContext();

   }

   return this.sslContext;

}

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("params不能为空!");

        }

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;

}

}

public Socket create(String host, int port, StringBuffer otherHeaders, BooleanHolder useFullURL) throws Exception {

return createSocket(host, (port == -1)?443:port);

}

}

3.webservice方式

package com.asiainfo.frame.utils;

import javax.xml.namespace.QName;

import org.apache.axis.AxisProperties;

import org.apache.axis.client.Call;

import org.apache.axis.client.Service;

import org.apache.commons.lang.StringUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

public class WebServiceUtils {

private static Logger logger = LoggerFactory.getLogger(WebServiceUtils.class);

static {

//处理https

AxisProperties.setProperty("axis.socketSecureFactory", "com.asiainfo.frame.utils.https.MyProtocolSocketFactory");

}

public static String send(String url, String method, String xml) throws Exception {

logger.info("url -> " + url);

logger.info("method -> " + method);

logger.info("xml -> " + xml);

Service service = new Service();

Call call = (Call)service.createCall();

call.setTargetEndpointAddress(url);

call.setOperationName(new QName("", method));

String result = null;

if(StringUtils.isNotEmpty(xml)){

result = (String)call.invoke(new Object[]{xml});

} else {

result = (String)call.invoke(new Object[]{});

}

logger.info("result -> " + result);

return result;

}

}

4.普通http方式

package com.asiainfo.frame.utils.https;

import java.io.File;

import java.io.InputStream;

import java.net.URLEncoder;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.methods.GetMethod;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.methods.multipart.FilePart;

import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;

import org.apache.commons.httpclient.methods.multipart.Part;

import org.apache.commons.httpclient.methods.multipart.StringPart;

import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.commons.httpclient.protocol.Protocol;

import org.apache.commons.lang.StringUtils;

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import com.asiainfo.frame.common.Constants;

@SuppressWarnings("deprecation")

public class HttpsClient {

private static Logger logger = LoggerFactory.getLogger(HttpsClient.class);

static {

//处理https

Protocol myhttps = new Protocol("https", new MyProtocolSocketFactory(null), 443);

Protocol.registerProtocol("https", myhttps);

}

/**

* Get方式请求(返回结果有转码)

* @param url

* @param params

* @return

*/

public static String doGet(String url, Map<String, ?> params) {

return doGet(url, params, true);

}

public static String doGet(String url, Map<String, ?> params, boolean encode, boolean... urlEncode) {

GetMethod getMethod = null;

try {

String sUrl = null;

if (params == null || params.size() == 0) {

sUrl = url;

} else {

StringBuffer buf = new StringBuffer();

for (String key : params.keySet()) {

String value = String.valueOf(params.get(key));

if(value != null){

if (buf.length() > 0) {

buf.append("&");

}

if(urlEncode.length == 0){

buf.append(key).append("=").append(URLEncoder.encode(value, Constants.ENCODE));

} else {

if(urlEncode[0]){

buf.append(key).append("=").append(URLEncoder.encode(value, Constants.ENCODE));

} else {

buf.append(key).append("=").append(value);

}

}

}

}

sUrl = url + "?" + buf.toString();

}

logger.info("sUrl -> " + sUrl);

getMethod = new GetMethod(sUrl);

HttpClient client = new HttpClient();

client.executeMethod(getMethod);

String result = null;

if(encode){

result = new String(getMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), Constants.ENCODE);

} else {

result = getMethod.getResponseBodyAsString();

}

logger.info("result -> " + result);

return result;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

if(getMethod != null){

getMethod.releaseConnection();

}

}

}

/**

* Post方式请求(返回结果有转码,请求内容为报文格式)

* @param url

* @param paramString

* @return

*/

public static String doPost(String url, String paramString) {

return doPost(url, paramString, true);

}

public static String doPost(String url, String paramString, boolean encode) {

logger.info("url -> " + url);

logger.info("paramString -> " + paramString);

PostMethod postMethod = null;

try {

postMethod = new PostMethod(url);

// 设置编码,防止中文乱码

postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, Constants.ENCODE);

if (paramString != null && paramString.length() > 0) {

postMethod.setRequestBody(paramString);

}

HttpClient client = new HttpClient();

client.executeMethod(postMethod);

String result = null;

if(encode){

result = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), Constants.ENCODE);

} else {

result = postMethod.getResponseBodyAsString();

}

logger.info("result -> " + result);

return result;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

if(postMethod != null){

postMethod.releaseConnection();

}

}

}

/**

* Post方式请求(返回结果有转码,请求内容为参数格式)

* @param url

* @param params

* @return

*/

public static String doPost(String url, Map<String, ?> params) {

return doPost(url, params, true);

}

public static String doPost(String url, Map<String, ?> params, boolean encode) {

logger.info("url -> " + url);

logger.info("params -> " + String.valueOf(params));

PostMethod postMethod = null;

try {

postMethod = new PostMethod(url);

if(params != null && params.size() > 0) {

NameValuePair[] pairArr = new NameValuePair[params.size()];

int i = 0;

for (String key : params.keySet()) {

pairArr[i] = new NameValuePair(key, String.valueOf(params.get(key)));

i++;

}

postMethod.setRequestBody(pairArr);

}

HttpClient client = new HttpClient();

client.executeMethod(postMethod);

String result = null;

if(encode){

result = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), Constants.ENCODE);

} else {

result = postMethod.getResponseBodyAsString();

}

logger.info("result -> " + result);

return result;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

if(postMethod != null){

postMethod.releaseConnection();

}

}

}

@SuppressWarnings("resource")

public static String doPostJson(String url, Map<String, ?> params, boolean encode) {

HttpPost postMethod = null;

try {

postMethod = new HttpPost(url);  

String jsonStr=JSON.toJSONString(params);

StringEntity entity = new StringEntity(jsonStr,"utf-8");//解决中文乱码问题    

entity.setContentEncoding("UTF-8"); 

entity.setContentType("application/json");    

postMethod.setEntity(entity);    

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpResponse result=httpClient.execute(postMethod);

String resData = EntityUtils.toString(result.getEntity()); 

System.out.println(resData);

return resData;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

if(postMethod != null){

postMethod.releaseConnection();

}

}

}

/**

* Post方式请求(返回结果有转码,请求内容为参数格式,带上传文件)

* @param url

* @param params

* @param name

* @param fileName

* @param file

* @return

*/

public static String doMultipartPost(String url, Map<String, ?> params, String name, String fileName, File file) {

logger.info("url -> " + url);

logger.info("params -> " + String.valueOf(params));

PostMethod postMethod = null;

try {

postMethod = new PostMethod(url);

List<Part> partList = new ArrayList<Part>();

if(params != null && params.size() > 0) {

for (String key : params.keySet()) {

partList.add(new StringPart(key, String.valueOf(params.get(key)), Constants.ENCODE));

}

}

if(StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(fileName) && file != null){

logger.info("name -> " + name + ", fileName -> " + fileName + ", file -> " + file.length());

partList.add(new FilePart(name, fileName, file));

}

Part[] parts = new Part[partList.size()];

parts = partList.toArray(parts);

postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

HttpClient client = new HttpClient();

client.executeMethod(postMethod);

String result = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), Constants.ENCODE);

logger.info("result -> " + result);

return result;

} catch (Exception e) {

throw new RuntimeException(e);

} finally {

if(postMethod != null){

postMethod.releaseConnection();

}

}

}

/**

* Post方式请求(返回结果为文件流,请求内容为报文格式)

* 注:postMethod不能释放,否则输出流会关闭

* @param url

* @param paramString

* @return

* @throws Exception

*/

public static InputStream doInputPost(String url, String paramString) throws Exception {

logger.info("url -> " + url);

logger.info("paramString -> " + paramString);

PostMethod postMethod = null;

try {

postMethod = new PostMethod(url);

// 设置编码,防止中文乱码

postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, Constants.ENCODE);

if (paramString != null && paramString.length() > 0) {

postMethod.setRequestBody(paramString);

}

HttpClient client = new HttpClient();

client.executeMethod(postMethod);

InputStream inputStream = postMethod.getResponseBodyAsStream();

logger.info("result -> available : " + inputStream.available());

return inputStream;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}

猜你喜欢

转载自flyer0428-qq-com.iteye.com/blog/2328004