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);
}
}
}
相关推荐
最后,`main.java`是程序的主入口,这里会调用前面创建的工具方法,整合所有步骤,完成实际的HTTPS请求: ```java public class Main { public static void main(String[] args) throws Exception { // 加载证书...
在Java开发中,调用HTTPS发布的Web Service接口是一项常见的任务,尤其在企业级应用中,HTTPS提供了安全的数据传输。本文将详细介绍如何使用Apache Axis库来实现这一功能,并提供相关步骤和注意事项。 首先,理解...
下面是如何在Java中实现HTTPS请求并跳过证书验证: 1. 创建一个TrustManager,它总是信任所有证书,不进行任何验证: ```java TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { ...
以下是一个使用HttpClient进行无证书验证调用HTTPS的示例。 首先,我们需要创建一个自定义的`SSLSocketFactory`,该工厂会忽略证书验证。这通常不推荐用于生产环境,因为它可能导致安全漏洞,但在测试或调试时非常...
使用java写的访问https网络协议的网址,绕过了证书的验证
在调用HTTPS服务时,Java会检查服务器的数字证书是否由受信任的证书颁发机构(CA)签署。`test_nciic.cer`文件可能是一个由测试环境提供的CA证书,我们需要将其添加到Java的信任存储库中。这可以通过以下步骤完成:...
在这个主题中,我们将深入探讨如何在Java中使用HttpClient来实现HTTPS接口调用。 首先,我们需要理解HTTPS协议。HTTPS是HTTP(超文本传输协议)与SSL/TLS(安全套接层/传输层安全)的结合,它为数据传输提供了加密...
### Java 发送 HTTPS 请求时遇到证书问题解析 在进行网络通信的过程中,HTTPS 协议由于其安全性被广泛应用。本文将围绕“Java 发送 HTTPS 请求证书问题”这一主题展开讨论,通过对给定文件中的代码示例及操作步骤...
Java调用OpenSSL生成证书是一种常见的安全操作,用于创建数字证书,这些证书在网络安全中扮演着重要角色,例如HTTPS通信、服务器身份验证等。在这个过程中,我们通常会使用OpenSSL命令行工具,然后通过Java程序来...
调用https协议的webservice,以及证书手动加载。
当你需要在Java程序中发送HTTPS请求时,可能会遇到证书相关的问题,特别是当服务器使用自签名证书或者非标准CA签发的证书时。本文将详细讲解如何在Java中处理这类问题,以及如何使用httpUtils工具进行HTTPS请求。 ...
在Java编程中,调用HTTPS协议是常见...总结来说,Java调用HTTPS涉及到SSL/TLS协议、证书管理、Socket工厂配置等多个环节。开发者需要理解这些概念,并在实际代码中正确处理证书和连接过程,以确保安全可靠的网络通信。
当你访问HTTPS站点时,Java默认的TrustStore可能不包含特定服务器的证书,因此需要自定义SSL上下文。首先,你需要将服务器的证书导入到一个信任库文件(如JKS或PKCS12格式),然后创建一个`SSLContext`对象,并设置...
java信任SSL证书的工具类 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
- 客户端代码则展示了如何通过CXF客户端API调用HTTPS服务,包括设置安全参数。 - Spring配置文件会包含服务bean和CXF相关配置,如端点地址、服务实现类等。 - 证书文件通常为`.pem`或`.jks`格式,用于建立安全...
Https请求工具类,Java实现http请求,https请求 本篇文章将详细介绍如何使用Java语言实现Http和Https请求的工具类,包括如何建立Https连接、如何实现Post请求、如何处理SSL验证等内容。 在Java中,使用...
java调用Gmssl中国密接口进行对称与非对称加解密等运算,动态so库进行接口jni方式调用,采取接口形式对外暴露,方便对接系统调用相关java接口进行相关运算操作。
net去调用java端写的https webservices 1)浏览器导入服务器cer证书 2)c#客户端引入证书