Http方式调用WebService,直接发送soap消息到服务端,然后自己解析服务端返回的结果,这种方式比较简单粗暴,也很好用;soap消息可以通过SoapUI来生成,也很方便。文中所使用到的软件版本:Java 1.8.0_191、Commons-HttpClient 3.1、HttpClient 4.5.10、HttpAsyncClient 4.1.4、Spring 5.1.9、dom4j 2.1.1、jackson 2.9.9、netty-all 4.1.33。

1、准备

参考Java调用WebService方法总结(1)--准备工作

2、调用

2.1、HttpURLConnection方式

该方式利用JDK自身提供的API来调用,不需要额外的JAR包。

public static void httpURLConnection(String soap) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlWsdl);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese");
connection.connect(); setBytesToOutputStream(connection.getOutputStream(), soap.getBytes());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] b = getBytesFromInputStream(connection.getInputStream());
String back = new String(b);
System.out.println("httpURLConnection返回soap:" + back);
System.out.println("httpURLConnection结果:" + parseResult(back));
} else {
System.out.println("httpURLConnection返回状态码:" + connection.getResponseCode());
} } catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
}

2.2、Commons-HttpClient方式

利用Apache Commons项目下的Commons-HttpClient组件调用,目前该组件已被HttpComponents项目所取代。

public static void commonsHttpClient(String soap) {
try {
org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod(urlWsdl);
post.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");
post.addRequestHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
org.apache.commons.httpclient.methods.RequestEntity entity = new org.apache.commons.httpclient.methods.InputStreamRequestEntity(new ByteArrayInputStream(soap.getBytes()));
post.setRequestEntity(entity);
int status = httpclient.executeMethod(post);
if (status == org.apache.commons.httpclient.HttpStatus.SC_OK) {
String back = post.getResponseBodyAsString();
System.out.println("Commons-HttpClinet返回soap:" + back);
System.out.println("commons-HttpClinet返回结果:" + parseResult(back));
} else {
System.out.println("commons-HttpClinet返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
}

2.3、HttpClient方式

利用Apache HttpComponents项目下HttpClient组件调用,是Commons-HttpClient组件的升级版。

public static void httpClient(String soap) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(urlWsdl);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String back = EntityUtils.toString(responseEntity);
System.out.println("httpClient返回soap:" + back);
System.out.println("httpClient返回结果:" + parseResult(back));
} else {
System.out.println("HttpClinet返回状态码:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}

2.4、HttpAsyncClient方式

HttpAsyncClient是HttpClient的异步版本,其用法跟HttpClient类似。

public static void httpAsyncClient(String soap) {
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
try {
httpClient.start();
HttpPost httpPost = new HttpPost(urlWsdl);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
httpPost.setEntity(entity);
Future<HttpResponse> future = httpClient.execute(httpPost, null);
HttpResponse response = future.get();
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String back = EntityUtils.toString(responseEntity);
System.out.println("HttpAsyncClient返回soap:" + back);
System.out.println("HttpAsyncClient返回结果:" + parseResult(back));
} else {
System.out.println("HttpAsyncClient返回状态码:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
}
}

2.5、RestTemplate方式

利用Srping的RestTemplate工具调用。

public static void restTemplate(String soap) {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("SOAPAction", targetNamespace + "toTraditionalChinese");
headers.add("Content-Type", "text/xml;charset=UTF-8");
org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(soap, headers);
ResponseEntity<String> response = template.postForEntity(urlWsdl, entity, String.class);
if (response.getStatusCode() == org.springframework.http.HttpStatus.OK) {
String back = template.postForEntity(urlWsdl, entity, String.class).getBody();
System.out.println("restTemplate返回soap:" + back);
System.out.println("restTemplate返回结果:" + parseResult(back));
} else {
System.out.println("restTemplate返回状态码:" + response.getStatusCode());
}
}

2.6、WebClient方式

利用Srping的WebClient工具调用,它是RestTemplate的异步版本。

public static void webClient(String soap) {
WebClient webClient = WebClient.create();
ResponseSpec response = webClient.post().uri(urlWsdl)
.header("SOAPAction", targetNamespace + "toTraditionalChinese")
.header("Content-Type", "text/xml;charset=UTF-8")
.syncBody(soap).retrieve();
Mono<String> mono = response.bodyToMono(String.class);
System.out.println("webClient返回soap:" + mono.block());
System.out.println("webClient结果:" + parseResult(mono.block()));
}

这种方式会用到reactor及nettty相关包:

reactor-core-3.3.0.RELEASE.jar(https://search.maven.org/artifact/io.projectreactor/reactor-core/3.3.0.RELEASE/jar)

reactive-streams-1.0.3.jar(https://search.maven.org/artifact/org.reactivestreams/reactive-streams/1.0.3/jar)

reactor-netty-0.9.1.RELEASE.jar(https://search.maven.org/artifact/io.projectreactor.netty/reactor-netty/0.9.1.RELEASE/jar)

netty-all-4.1.33.Final.jar(https://search.maven.org/artifact/io.netty/netty-all/4.1.33.Final/jar)

2.7、小结

几种方式其实差不多,主体思想是一样的就是发送soap报文,就是写法不一样而已。完整例子:

package com.inspur.ws;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import reactor.core.publisher.Mono; /**
* Http方式调用WebService
*
*/
public class Http {
private static String urlWsdl = "http://www.webxml.com.cn/WebServices/TraditionalSimplifiedWebService.asmx?wsdl";
private static String targetNamespace = "http://webxml.com.cn/"; /**
* HttpURLConnection方式
* @param soap
*/
public static void httpURLConnection(String soap) {
HttpURLConnection connection = null;
try {
URL url = new URL(urlWsdl);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese");
connection.connect(); setBytesToOutputStream(connection.getOutputStream(), soap.getBytes());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
byte[] b = getBytesFromInputStream(connection.getInputStream());
String back = new String(b);
System.out.println("httpURLConnection返回soap:" + back);
System.out.println("httpURLConnection结果:" + parseResult(back));
} else {
System.out.println("httpURLConnection返回状态码:" + connection.getResponseCode());
} } catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
} /**
* Commons-HttpClinet方式
* @param soap
*/
public static void commonsHttpClient(String soap) {
try {
org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod(urlWsdl);
post.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");
post.addRequestHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
org.apache.commons.httpclient.methods.RequestEntity entity = new org.apache.commons.httpclient.methods.InputStreamRequestEntity(new ByteArrayInputStream(soap.getBytes()));
post.setRequestEntity(entity);
int status = httpclient.executeMethod(post);
if (status == org.apache.commons.httpclient.HttpStatus.SC_OK) {
String back = post.getResponseBodyAsString();
System.out.println("Commons-HttpClinet返回soap:" + back);
System.out.println("commons-HttpClinet返回结果:" + parseResult(back));
} else {
System.out.println("commons-HttpClinet返回状态码:" + status);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* HttpClient方式
* @param soap
*/
public static void httpClient(String soap) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(urlWsdl);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String back = EntityUtils.toString(responseEntity);
System.out.println("httpClient返回soap:" + back);
System.out.println("httpClient返回结果:" + parseResult(back));
} else {
System.out.println("HttpClinet返回状态码:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* HttpAsyncClient方式
* @param soap
*/
public static void httpAsyncClient(String soap) {
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
try {
httpClient.start();
HttpPost httpPost = new HttpPost(urlWsdl);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
httpPost.setEntity(entity);
Future<HttpResponse> future = httpClient.execute(httpPost, null);
HttpResponse response = future.get();
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String back = EntityUtils.toString(responseEntity);
System.out.println("HttpAsyncClient返回soap:" + back);
System.out.println("HttpAsyncClient返回结果:" + parseResult(back));
} else {
System.out.println("HttpAsyncClient返回状态码:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
}
} /**
* RestTemplate方式
* @param soap
*/
public static void restTemplate(String soap) {
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("SOAPAction", targetNamespace + "toTraditionalChinese");
headers.add("Content-Type", "text/xml;charset=UTF-8");
org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(soap, headers);
ResponseEntity<String> response = template.postForEntity(urlWsdl, entity, String.class);
if (response.getStatusCode() == org.springframework.http.HttpStatus.OK) {
String back = template.postForEntity(urlWsdl, entity, String.class).getBody();
System.out.println("restTemplate返回soap:" + back);
System.out.println("restTemplate返回结果:" + parseResult(back));
} else {
System.out.println("restTemplate返回状态码:" + response.getStatusCode());
}
} /**
* WebClient方式
* @param soap
*/
public static void webClient(String soap) {
WebClient webClient = WebClient.create();
ResponseSpec response = webClient.post().uri(urlWsdl)
.header("SOAPAction", targetNamespace + "toTraditionalChinese")
.header("Content-Type", "text/xml;charset=UTF-8")
.syncBody(soap).retrieve();
Mono<String> mono = response.bodyToMono(String.class);
System.out.println("webClient返回soap:" + mono.block());
System.out.println("webClient结果:" + parseResult(mono.block()));
} /**
* 从输入流获取数据
* @param in
* @return
* @throws IOException
*/
private static byte[] getBytesFromInputStream(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = in.read(b)) != -1) {
baos.write(b, 0, len);
}
byte[] bytes = baos.toByteArray();
return bytes;
} /**
* 向输入流发送数据
* @param out
* @param bytes
* @throws IOException
*/
private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
byte[] b = new byte[1024];
int len;
while ((len = bais.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
} /**
* 解析结果
* @param s
* @return
*/
private static String parseResult(String s) {
String result = "";
try {
Reader file = new StringReader(s);
SAXReader reader = new SAXReader(); Map<String, String> map = new HashMap<String, String>();
map.put("ns", "http://webxml.com.cn/");
reader.getDocumentFactory().setXPathNamespaceURIs(map);
Document dc = reader.read(file);
result = dc.selectSingleNode("//ns:toTraditionalChineseResult").getText().trim();
} catch (Exception e) {
e.printStackTrace();
}
return result;
} public static void main(String[] args) {
String soap11 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webxml.com.cn/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<web:toTraditionalChinese>"
+ "<web:sText>小学</web:sText>"
+ "</web:toTraditionalChinese>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
String soap12 = "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://webxml.com.cn/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<web:toTraditionalChinese>"
+ "<web:sText>大学</web:sText>"
+ "</web:toTraditionalChinese>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
httpURLConnection(soap11);
httpURLConnection(soap12); commonsHttpClient(soap11);
commonsHttpClient(soap12); httpClient(soap11);
httpClient(soap12); httpAsyncClient(soap11);
httpAsyncClient(soap12); restTemplate(soap11);
restTemplate(soap12); webClient(soap11);
webClient(soap12);
}
}

Java调用WebService方法总结(9,end)--Http方式调用WebService的更多相关文章

  1. Java 7新方法probeContentType的C#实现方式

    在Java 7中增加了新的一个方法——probeContentType,其主要作用是可以判断文件的content type.相应代码如下所示: import java.io.IOException; ...

  2. Java项目main方法启动的两种方式

    1.打包时指定了主类,可以直接用java -jar xxx.jar. <!--main方法打包jar包插件--> <plugin> <artifactId>mave ...

  3. Java调用WebService方法总结(1)--准备工作

    WebService是一种跨编程语言.跨操作系统平台的远程调用技术,已存在很多年了,很多接口也都是通过WebService方式来发布的:本系列文章主要介绍Java调用WebService的各种方法,使 ...

  4. RTX——第19章 SVC 中断方式调用用户函数(后期补历程)

    以下内容转载自安富莱电子: http://forum.armfly.com/forum.php 本章节为大家讲解如何采用 SVC 中断方式调用用户函数. 当用户将 RTX 任务设置为工作在非特权级模式 ...

  5. Java调用WebService方法总结(8)--soap.jar调用WebService

    Apache的soap.jar是一种历史很久远的WebService技术,大概是2001年左右的技术,所需soap.jar可以在http://archive.apache.org/dist/ws/so ...

  6. Java调用WebService方法总结(7)--CXF调用WebService

    CXF = Celtix + XFire,继承了Celtix和XFire两大开源项目的精华,是一个开源的,全功能的,容易使用的WebService框架.文中所使用到的软件版本:Java 1.8.0_1 ...

  7. Java调用WebService方法总结(6)--XFire调用WebService

    XFire是codeHaus组织提供的一个WebService开源框架,目前已被Apache的CXF所取代,已很少有人用了,这里简单记录下其调用WebService使用方法.官网现已不提供下载,可以到 ...

  8. Java调用WebService方法总结(5)--Axis2调用WebService

    Axis2是新一点Axis,基于新的体系结构进行了全新编写,有更强的灵活性并可扩展到新的体系结构.文中demo所使用到的软件版本:Java 1.8.0_191.Axis2 1.7.9. 1.准备 参考 ...

  9. Java调用WebService方法总结(4)--Axis调用WebService

    Axis是比较常用的WebService框架,该项目在2006实现了最终版,后面就没有更新了.文中demo所使用到的软件版本:Java 1.8.0_191.Axis 1.4. 1.准备 参考Java调 ...

随机推荐

  1. 273道题目;更新到java题目里面 (已迁移到其他类目下面,存储)

    1. Java 基础 1.JDK 和 JRE 有什么区别? 2. == 和 equals 的区别是什么? 3. 两个对象的 hashCode() 相同,则 equals() 也一定为 true,对吗? ...

  2. hdu1237 简单计算器[STL 栈]

    目录 题目地址 题干 代码和解释 参考 题目地址 hdu1237 题干 代码和解释 解本题时使用了STL 栈,要记得使用#include<stack>. 解本题时使用了isdigit()函 ...

  3. PHP系列 | PHP5.6 安装 endroid/qr-code 遇到的问题

    官方库地址:https://packagist.org/packages/endroid/qr-code PHP5.6 的最高版本为:2.5.1 通过composer安装 composer requi ...

  4. IDEA2019.2.1中文乱码解决

    写在前面 太晚了, 长话短说, idea更新到2019.2.1, 项目任何地方输入中文都是乱码, 修改编码UTF-8依然如此.参考https://blog.csdn.net/chenjk10/arti ...

  5. js实现字符串切割并转换成对象格式保存到本地

    // split() 将字符串按照指定的规则分割成字符串数组,并返回此数组(字符串转数组的方法) //分割字符串 var bStr = "www.baidu.con"; var a ...

  6. filebeat获取nginx的access日志配置

    filebeat获取nginx的access日志配置 产生nginx日志的服务器即生产者服务器配置: 拿omp.chinasoft.com举例: .nginx.conf主配置文件添加日志格式 log_ ...

  7. Spring cloud微服务安全实战-6-10sentinel之热点和系统规则

    热点规则 热点就是经常访问的数据.很多时候我们希望争对某一些热点数据,然后来进行限制.比如说商品的信息这个服务,我们给它做一个限流,qps是100,某一天我想做一个秒杀活动,可能会有很大的流量,这个时 ...

  8. 【各种误解解释】C-LODOP的三种角色及注册号

    该简短问答是从现象和误解和相关作为分类,主要是注册角色和注册号使用等.之前的相关博文(该相关博也有些链接到的博文,按照大类区分):LODOP和C-LODOP注册与角色等简短问答[增强版]. 确认角色: ...

  9. [LeetCode] 355. Design Twitter 设计推特

    Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...

  10. [LeetCode] 597. Friend Requests I: Overall Acceptance Rate 朋友请求 I: 全部的接受率

    In social network like Facebook or Twitter, people send friend requests and accept others’ requests ...