虽然 WebService 这个框架已经过时,但是有些公司还在使用,在调用他们的服务的时候就不得不面对各种问题,本篇文章总结了最近我调用他司 WebService 的心路历程。3 种方式可以分别尝试,哪种能通用哪个。
soapui 下载地址:百度网盘、夸克网盘。
1. HttpClient
依赖:
<!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- Apache Http httpclient_version--><dependency><groupId>org.apache.httpcomponents.client5</groupId><artifactId>httpclient5</artifactId><version>5.1.3</version></dependency>
代码:
importlombok.extern.slf4j.Slf4j;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.HttpEntity;@Slf4jpublicclassHttpClientUtil{/**
* HttpClient 调用 WebService
* @param wsUrl webService地址,格式:http://ip:port/xxx/xxx/soap?wsdl
* @param json格式的入参
* @return
*/publicstaticStringcallServiceHC(String wsUrl,String jsonStr){String xml =createSoapContent(jsonStr);String returnDatabase =doPostSoap(wsUrl, xml,"");
log.info("returnDatabase===>{}", returnDatabase);return returnDatabase;}/**
* 根据拼接 xml 字符串
* @param input
* @return
*/publicstaticStringcreateSoapContent(String jsonStr){
log.info("开始拼接请求报文");//开始拼接请求报文StringBuilder stringBuilder =newStringBuilder();
stringBuilder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:zys=\"http://www.chenjy.com.cn/\">\n");
stringBuilder.append("<soapenv:Header/>\n");
stringBuilder.append("<soapenv:Body>\n");
stringBuilder.append("<cjy:CallInterface>\n");
stringBuilder.append("<cjy:msgHeader><![CDATA[\n");
stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
stringBuilder.append("<root>\n");
stringBuilder.append("<serverName>getInfo</serverName>\n");
stringBuilder.append("<format>xml</format>\n");
stringBuilder.append("<callOperator>测试</callOperator>\n");
stringBuilder.append("<certificate>AcsaoP21Lxw5KAoQu6SLs624bhGjwNL0DzxsQ9a7B/HbqNsPPcA==</certificate>\n");
stringBuilder.append("</root>\n");
stringBuilder.append("]]></cjy:msgHeader>\n");
stringBuilder.append("<cjy:msgBody><![CDATA[\n");
stringBuilder.append( jsonStr+"\n");
stringBuilder.append("]]></cjy:msgBody>\n");
stringBuilder.append("</cjy:CallInterface>\n");
stringBuilder.append("</soapenv:Body>\n");
stringBuilder.append("</soapenv:Envelope>");
log.info("拼接后的参数"+stringBuilder.toString());return stringBuilder.toString();}/**
* HTTPClient 调用 WebService
* @param url
* @param soap
* @param SOAPAction
* @return
*/publicstaticStringdoPostSoap(String url,String soap,StringSOAPAction){//请求体String retStr ="";// 创建HttpClientBuilderHttpClientBuilder httpClientBuilder =HttpClientBuilder.create();// HttpClientCloseableHttpClient closeableHttpClient = httpClientBuilder.build();HttpPost httpPost =newHttpPost(url);try{
httpPost.setHeader("Content-Type","text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction",SOAPAction);StringEntity data =newStringEntity(soap,Charset.forName("UTF-8"));
httpPost.setEntity(data);CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);HttpEntity httpEntity = response.getEntity();if(httpEntity !=null){// 打印响应内容
retStr =EntityUtils.toString(httpEntity,"UTF-8");}// 释放资源
closeableHttpClient.close();}catch(Exception e){
e.printStackTrace();}return retStr;}}
注意:拼接 xml 字符串的时候要根据实际的 WebService 地址拼接,可在 soapui 中导入 wsurl 获取到入参,如下:
把这些参数全部拼接进去:
补充:忽略 ssl 验证,调用WebService接口
publicstaticStringsendPostByHttpsWithoutSSL(String url,String body,StringSOAPAction){SSLConnectionSocketFactory sslConnectionSocketFactory =null;try{
sslConnectionSocketFactory =newSSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial(null,newTrustStrategy(){@OverridepublicbooleanisTrusted(X509Certificate[] x509Certificates,String s)throwsCertificateException{returntrue;}}).build(),NoopHostnameVerifier.INSTANCE);}catch(NoSuchAlgorithmException|KeyManagementException|KeyStoreException e){
e.printStackTrace();}CloseableHttpClient httpClient =HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();//创建post方式请求对象HttpPost httpPost =newHttpPost(url);// 请求头设置
httpPost.setHeader("Content-Type","text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction",SOAPAction);// 情求体设置if(body !=null){
httpPost.setEntity(newStringEntity(body,"utf-8"));}CloseableHttpResponse response =null;//执行请求操作,并拿到结果try{
response = httpClient.execute(httpPost);//获取结果实体HttpEntity entity = response.getEntity();String respBody;if(entity !=null){
respBody =EntityUtils.toString(entity);return respBody;}}catch(IOException e){}returnnull;}
2. Http post
依赖:
<!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- jodd-http --><dependency><groupId>org.jodd</groupId><artifactId>jodd-http</artifactId><version>6.3.0</version></dependency>
代码:
importlombok.extern.slf4j.Slf4j;importjodd.http.*;publicclassHttpPostUtil{/**
* http post 调用 WebService
* @param wsUrl
* @param jsonStr
* @return
*/publicstaticStringcallServiceHP(String wsUrl,String jsonStr){String xml =createSoapContent(jsonStr);String uploadFeeDetailJsonStr =postWs(wsUrl, xml);return uploadFeeDetailJsonStr;}/**
* 根据拼接 xml 字符串
* @param input
* @return
*/publicstaticStringcreateSoapContent(String jsonStr){
log.info("开始拼接请求报文");//开始拼接请求报文StringBuilder stringBuilder =newStringBuilder();
stringBuilder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:zys=\"http://www.chenjy.com.cn/\">\n");
stringBuilder.append("<soapenv:Header/>\n");
stringBuilder.append("<soapenv:Body>\n");
stringBuilder.append("<cjy:CallInterface>\n");
stringBuilder.append("<cjy:msgHeader><![CDATA[\n");
stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
stringBuilder.append("<root>\n");
stringBuilder.append("<serverName>getInfo</serverName>\n");
stringBuilder.append("<format>xml</format>\n");
stringBuilder.append("<callOperator>测试</callOperator>\n");
stringBuilder.append("<certificate>AcsaoP21Lxw5KAoQu6SLs624bhGjwNL0DzxsQ9a7B/HbqNsPPcA==</certificate>\n");
stringBuilder.append("</root>\n");
stringBuilder.append("]]></cjy:msgHeader>\n");
stringBuilder.append("<cjy:msgBody><![CDATA[\n");
stringBuilder.append( jsonStr+"\n");
stringBuilder.append("]]></cjy:msgBody>\n");
stringBuilder.append("</cjy:CallInterface>\n");
stringBuilder.append("</soapenv:Body>\n");
stringBuilder.append("</soapenv:Envelope>");
log.info("拼接后的参数"+stringBuilder.toString());return stringBuilder.toString();}/**
* 调用 webService
* @param url
* @param jsonStr
* @return
*/publicstaticStringpostWs(String url,String jsonStr){HttpResponse resp =HttpRequest.post(url).connectionTimeout(60000).timeout(60000).contentType("application/xml",StandardCharsets.UTF_8.toString()).header("SOAPAction","").bodyText(jsonStr,"application/xml","utf-8").charset(StandardCharsets.UTF_8.toString()).trustAllCerts(true).send();
resp.charset(StandardCharsets.UTF_8.toString());return resp.bodyText();}}
3. cxf
因为我用 cxf 调不通,所以就在这里就直接奉上其他博主的调用案例:
https://blog.csdn.net/qq_20161461/article/details/116237450
版权归原作者 364.99° 所有, 如有侵权,请联系我们删除。