需求:我方生成数据调用三方系统接口将数据传输。
流程:数据生成csv文件-压缩-加密-调接口传输数据,此处只放调三方系统接口的代码,生成csv文件、压缩、加密等实例网上很多了自行搜索吧 0.0。
环境:windows系统,javajdk1.7,eclipse
开胃“小菜”: jdk1.7 支持协议 :SSLv2Hello 、SSLv3、TLSv1、TLSv1.1、TLSv1.2五种协议,但是默认协议是:TLSv1,因为https 请求是双向认证的也就是jdk的支持协议最低是TLSv1以上的版本,所有jdk1.7不能访问https请求。
1、新建java类文件:TrustAnyHostnameVerifier
package com.fast_materie.hzya.materie;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
// 直接Pass
return true;
}
}
2、新建java类文件:TrustAnyTrustManager
package com.fast_materie.hzya.materie;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
import com.fast_materie.hzya.materie.SslUtil;
import com.google.common.collect.Maps;
public class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] x509Certificates, String s) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
3、调三方系统接口核心代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Encoder;
import com.fast_materie.hzya.materie.SslUtil;
import com.google.common.collect.Maps;
//string参数:密文数据
public String sendPost(String string) throws UnsupportedEncodingException {
writeNcLog("---进入物料推送********系统程序---");
String result = "";
try {
writeNcLog("忽略HTTPS请求的SSL证书。");
SslUtil.ignoreSsl();
writeNcLog("开始初始化数据推送所需参数...");
//接口地址
URL url = new URL("********");
//接口要验证的用户名
String wasUserName = "********";
//验证密码
String wasPassword = "********";
//认证
String authorization = "Basic "
+ new String(Base64.encodeBase64(new String(wasUserName + ":"
+ wasPassword).getBytes()));
writeNcLog("初始化数据推送所需参数完成。");
writeNcLog("创建http链接对象。");
//获取连接
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
if (con instanceof HttpsURLConnection) {
writeNcLog("获取TLSv1.2协议实例。");
SSLContext sc = SSLContext.getInstance("TLSv1.2");
writeNcLog("初始化TLSv1.2协议实例。");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
((HttpsURLConnection) con).setSSLSocketFactory(sc
.getSocketFactory());
((HttpsURLConnection) con)
.setHostnameVerifier(new TrustAnyHostnameVerifier());
}
//设置接口请求所需参数
con.setRequestProperty("Authorization", authorization);
con.setRequestProperty("Content-Type","text/xml");
// 设置请求方式
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
//本业务所需的数据(自行更改)
String requestXml = "SA 0020146981 D01_900 https://s1.sapariba.cn:443/Sourcing/fileupload?realm=chint-T http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous uuid:00155d00-f614-1ed9-9eed-edb4dbb6da6d chint-T true Import External System Master Data DirectConnect CI9-DirectConnect 10.1.110.177-WJIAB Load SAP "
+ string
+ " ";
String payload = requestXml;
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream());
osw.write(payload);
osw.flush();
osw.close();
// 获取请求状态 code 和 Message
int requestStatus = con.getResponseCode();
String requestMessage = con.getResponseMessage();
writeNcLog("接口响应状态码:"+requestStatus+",接口响应信息:"+requestMessage);
writeNcLog("---物料推送********系统程序执行完成---");
} catch (Exception e) {
writeNcLog(e.getMessage());
}
return result;
}
4、新建类SslUtil
package com.fast_materie.hzya.materie;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
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;
import org.apache.commons.io.IOUtils;
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之前调用
*
* @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);
}
public static String getRequest(String url, int timeOut) throws Exception {
URL u = new URL(url);
if ("https".equalsIgnoreCase(u.getProtocol())) {
SslUtil.ignoreSsl();
}
URLConnection conn = u.openConnection();
conn.setConnectTimeout(timeOut);
conn.setReadTimeout(timeOut);
return IOUtils.toString(conn.getInputStream());
}
public static String postRequest(String urlAddress, String args, int timeOut)
throws Exception {
URL url = new URL(urlAddress);
if ("https".equalsIgnoreCase(url.getProtocol())) {
SslUtil.ignoreSsl();
}
URLConnection u = url.openConnection();
u.setDoInput(true);
u.setDoOutput(true);
u.setConnectTimeout(timeOut);
u.setReadTimeout(timeOut);
OutputStreamWriter osw = new OutputStreamWriter(u.getOutputStream(),
"UTF-8");
osw.write(args);
osw.flush();
osw.close();
u.getOutputStream();
return IOUtils.toString(u.getInputStream());
}
}
参考博文:JDK1.7不支持Https TLS1.2协议
到此核心代码差不多就这些,对了!部署到客户测试服务器的时候不要忘了客户测试服务器要有网,否则接口是调不通的总是报:handle failure错误,有什么疑问评论就可以。仅是一个小白记录一下防止忘记,大佬勿喷.....