java调用三方系统带验证的接口

需求:我方生成数据调用三方系统接口将数据传输。

流程:数据生成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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap-env:Header><m:CallerInformation xmlns:m=\"http://www.sap.com/webas/712/soap/features/runtime/metering/\"><m:Type>SA</m:Type><m:Company>0020146981</m:Company><m:Sys>D01_900</m:Sys></m:CallerInformation><wsa:To soap-env:mustUnderstand=\"1\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">https://s1.sapariba.cn:443/Sourcing/fileupload?realm=chint-T</wsa:To><wsa:From xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address></wsa:From><wsa:ReplyTo xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address></wsa:ReplyTo><wsa:FaultTo xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"><wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address></wsa:FaultTo><wsa:Action soap-env:mustUnderstand=\"1\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\"/><wsa:MessageID xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">uuid:00155d00-f614-1ed9-9eed-edb4dbb6da6d</wsa:MessageID></soap-env:Header><soap-env:Body><n0:MT_UploadReq xmlns:n0=\"http://ariba.com/xi/AribaUpload\" xmlns:prx=\"urn:sap.com:proxy:D01:/1SAI/TASBF2F26173F170031754F:740\"><Header><Parameters><Parameter name=\"realm\"><value>chint-T</value></Parameter><Parameter name=\"fullload\"><value>true</value></Parameter><Parameter name=\"event\"><value>Import External System Master Data</value></Parameter><Parameter name=\"clienttype\"><value>DirectConnect</value></Parameter><Parameter name=\"clientversion\"><value>CI9-DirectConnect</value></Parameter><Parameter name=\"clientinfo\"><value>10.1.110.177-WJIAB</value></Parameter><Parameter name=\"operation\"><value>Load</value></Parameter><Parameter name=\"systemId\"><value>SAP</value></Parameter></Parameters><AttachmentFolder contentID=\"FOL33000000000004EXT39000000000138\" contentType=\"application/zip\" fileName=\"processing20190521102332_1.zip\" contentLength=\"2040\"><Content>"
					+ string
					+ "</Content></AttachmentFolder></Header></n0:MT_UploadReq></soap-env:Body></soap-env:Envelope>";
			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错误,有什么疑问评论就可以。仅是一个小白记录一下防止忘记,大佬勿喷.....

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值