本文章向大家介绍 https访问带有SOAP协议头,需要用户验证的webservice接口,主要包括https请求SOAP webService接口使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
模拟soapui调用webservice
publicstaticStringsoapSpecialConnection(Stringurl,Stringparams) throwsException { Strings=newString(); StringBuildersoapHeader=newStringBuilder(); // 传来字符串参数 soapHeader.append(params); System.out.println("soapHeader=" + soapHeader); // 设置soap请求报文的相关属性 // url从soapUI的request1的RAW标签的POST获取,url中不要有空格 URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setDefaultUseCaches(false); // Host,Content-Type,SOAPAction从soapUI的request1的RAW标签的Host,Content-Typ,SOAPActione获取 conn.setRequestProperty("Host", "test.com:95443"); conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Authorization", "Basic ABCBCBC"); conn.setRequestProperty("Content-Length", String.valueOf(soapHeader.length())); conn.setRequestProperty("SOAPAction", ""); conn.setRequestProperty("Username", "AAAAA"); conn.setRequestProperty("Password", "BBBB"); // 定义输出流 OutputStream output = conn.getOutputStream(); if (null != soapHeader) { byte[] b = soapHeader.toString().getBytes("utf-8"); // 发送soap请求报文 output.write(b, 0, b.length); } output.flush(); output.close(); // 定义输入流,获取soap响应报文 InputStream input = conn.getInputStream(); // 需设置编码格式,否则会乱码 s = IOUtils.toString(input, "UTF-8"); input.close(); System.out.println("输出的xml=" + s); return s; }
既然是HTTPS请求,就需要绕过证书并击中web服务,使HTTPS SOAP请求绕过SSL证书。
public class ConnectHttps { public static void main(String[] args) throws Exception { /* * fix for * Exception in thread "main" javax.net.ssl.SSLHandshakeException: * sun.security.validator.ValidatorException: * PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: * unable to find valid certification path to requested target */ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); /* * end of the fix */ } }
客户端调用
String webServiceAndSoap = soapSpecialConnection(url,requestXml);System.out.println(webServiceAndSoap);
以上是https请求SOAP webService接口全部内容了。大家喜欢记得关注公主号【全栈芬达】,记得点赞哦!