webservice框架有很多,比如axis、axis2、cxf、xFire等等,做服务端和做客户端都可行,个人感觉使用这些框架的好处是减少了对于接口信息的解析,最主要的是减少了对于传递于网络中XML的解析,代价是你不得不在你的框架中添加对于这些框架的依赖。个人观点是:服务端使用这些框架还行,如果做客户端,没必要使用这些框架,只需使用httpclient即可。

一、创建并发布一个简单的webservice应用

  1、webservice 代码:

 import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint; @WebService
public class HelloWorld {
@WebMethod
public String sayHello(String str){
System.out.println("get Message...");
String result = "Hello World, "+str;
return result;
}
public static void main(String[] args) {
System.out.println("server is running");
String address="http://localhost:9000/HelloWorld";
Object implementor =new HelloWorld();
Endpoint.publish(address, implementor);
} }

  2、运行项目,并访问 "http://localhost:9000/HelloWorld?wsdl",得到wsdl文件,说明webservice发布成功

  例如天气的wsdl:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

二、客户端访问webservice

  1、通过 HttpClient 及  HttpURLConnection 发送SOAP请求,代码如下: 

  import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils; public class TestHelloWrold {
public static void main(String[] args) throws Exception {
String wsdl = "http://localhost:9000/HelloWorld?wsdl";
int timeout = 10000;
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<soap:Envelope "
+ "xmlns:api='http://demo.ls.com/' "
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
+ "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
+ "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
sb.append("<soap:Body>");
sb.append("<api:sayHello>");
sb.append("<arg0>ls</arg0>");
sb.append("</api:sayHello>");
sb.append("</soap:Body>");
sb.append("</soap:Envelope>"); // HttpClient发送SOAP请求
System.out.println("HttpClient 发送SOAP请求");
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(wsdl);
// 设置连接超时
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
// 设置读取时间超时
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
// 然后把Soap请求数据添加到PostMethod中
RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
//设置请求头部,否则可能会报 “no SOAPAction header” 的错误
postMethod.setRequestHeader("SOAPAction","");
// 设置请求体
postMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(postMethod);
// 打印请求状态码
System.out.println("status:" + status);
// 获取响应体输入流
InputStream is = postMethod.getResponseBodyAsStream();
// 获取请求结果字符串
String result = IOUtils.toString(is);
System.out.println("result: " + result); // HttpURLConnection 发送SOAP请求
System.out.println("HttpURLConnection 发送SOAP请求");
URL url = new URL(wsdl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout); DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.write(sb.toString().getBytes("utf-8"));
dos.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
StringBuffer strBuf = new StringBuffer();
while ((line = reader.readLine()) != null) {
strBuf.append(line);
}
dos.close();
reader.close(); System.out.println(strBuf.toString());
}
}

  响应报文如下:

<?xml version="1.0" ?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
      <ns2:sayHelloResponse xmlns:ns2="http://demo.ls.com/">
        <return>Hello World, ls</return>
      </ns2:sayHelloResponse>
    </S:Body>
  </S:Envelope>

SOAP的请求报文的格式是怎么来的呢?

 (1)可用Eclipse测试WSDL文件,则可得到想要的SOAP请求及响应报文,具体步骤如下图:

   第一步:

    

  第二步:

  通过第一步,会在浏览器打开如下的页面

  

 (2)saopui工具拿到soap报文

  soapUI是一个开源测试工具,通过soap/http来检查、调用、实现Web Service的功能/负载/符合性测试。该工具既可作为一个单独的测试软件使用,也可利用插件集成到Eclipse,maven2.X,Netbeans 和intellij中使用。soapUI pro是soapUI的商业非开源版本,实现的 功能较开源的soapUI更多。

  a、首先得安装soapUI 4.5.2,安装后打开,截图如下:

    

  b、右键点击“Projects”创建工程,截图如下:

    

  c、双击展开左侧创建的工程下所有节点,最后双击“Request 1”节点,在右侧即可拿到soap格式消息,这个就是我们后面作为客户端调用服务端的报文内容,截图如下:

    

2、生成客户端代码访问

   a、通过 "wsimport"(JDK自带)命令生成客户端代码。进入命令行模式,执行 wsimport -s . http://localhost:9000/HelloWorld?wsdl,就会在当前目录下生成客户端代码。附图:

    

     b、通过Eclipse生成客户端代码

    

    

  (1).生成本地代码后可以直接调用,比如调用天气webservice接口: 

package hanwl.TestDemo;

import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import cn.com.WebXml.WeatherWebService;
import cn.com.WebXml.WeatherWebServiceLocator;
import cn.com.WebXml.WeatherWebServiceSoap; public class TestWebservice {
public static void main(String[] args) {
WeatherWebService weatherWebService = new WeatherWebServiceLocator();
WeatherWebServiceSoap weatherWebServiceSoap = null;
try {
weatherWebServiceSoap = weatherWebService.getWeatherWebServiceSoap();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} String[] cityweather = null;
//String[] city={"北京","上海","深圳","广州"};
try {
cityweather = weatherWebServiceSoap.getWeatherbyCityName("北京");//不输入默认为上海市
} catch (RemoteException e) {
e.printStackTrace();
} for(String s :cityweather){
System.out.println(s);
System.out.println("------------------------");
}
} }

  (2).httpclient作为客户端调用天气webservice

package hanwl.TestDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xml.sax.InputSource; public class TestWebservice2 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub
String wsdl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
int timeout = 1000;
StringBuffer sb = new StringBuffer("");
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<soapenv:Envelope "
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
+ " xmlns:q0='http://WebXml.com.cn/' "
+ " xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
+ " xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' >");
sb.append("<soapenv:Body>");
sb.append("<q0:getWeatherbyCityName>");
sb.append("<q0:theCityName>唐山</q0:theCityName> ");
sb.append("</q0:getWeatherbyCityName>");
sb.append("</soapenv:Body>");
sb.append("</soapenv:Envelope>"); // HttpClient发送SOAP请求
System.out.println("HttpClient 发送SOAP请求");
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(wsdl);
// 设置连接超时
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
// 设置读取时间超时
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
// 然后把Soap请求数据添加到PostMethod中
RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
//设置请求头部,否则可能会报 “no SOAPAction header” 的错误
//postMethod.setRequestHeader("SOAPAction","");
// 设置请求体
postMethod.setRequestEntity(requestEntity);
int status = client.executeMethod(postMethod);
// 打印请求状态码
System.out.println("status:" + status);
// 获取响应体输入流
InputStream is = postMethod.getResponseBodyAsStream();
// 获取请求结果字符串
String result = IOUtils.toString(is);
Document dc = strXmlToDocument(result);
// Element root = dc.getRootElement();
// System.out.println(root.getName());
// System.out.println("result: " + result); } public static Document strXmlToDocument(String parseStrXml){
Document document = null;
try {
document = DocumentHelper.parseText(parseStrXml);
Element root = document.getRootElement();
List<Element> list = root.elements();
getElement(list);
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
} private static void getElement(List<Element> sonElemetList) {
// Map<String,String> map = new HashMap<String, String>();
for (Element sonElement : sonElemetList) {
if (sonElement.elements().size() != 0) {
System.out.println(sonElement.getName() + ":");
getElement(sonElement.elements());
}else{
System.out.println(sonElement.getName() + ":"+ sonElement.getText());
} }
}
}

三、总结

优点:

1.使用httpclient作为客户端调用webservice,不用关注繁琐的webservice框架,只需找到SOAP消息格式,添加httpclient依赖就行。

2.使用httpclient调用webservice,建议采用soap1.1方式调用,经测试使用soap1.1方式能调用soap1.1和soap1.2的服务端。

缺点:

唯一的缺点是,你得自己解析返回的XML,找到你关注的信息内容。

参考地址:https://blog.csdn.net/zilong_zilong/article/details/53932667

     https://blog.csdn.net/gzxdale/article/details/74242359

Java发布webservice应用并发送SOAP请求调用的更多相关文章

  1. Java发布一个简单 webservice应用 并发送SOAP请求

    一.创建并发布一个简单的webservice应用 1.webservice 代码: package com.ls.demo; import javax.jws.WebMethod; import ja ...

  2. Java 发送SOAP请求调用WebService,解析SOAP报文

    https://blog.csdn.net/Peng_Hong_fu/article/details/80113196 记录测试代码 SoapUI调用路径 http://localhost:8082/ ...

  3. Jmeter发送SOAP请求对WebService接口测试

    Jmeter发送SOAP请求对WebService接口测试 1.测试计划中添加一个用户自定义变量 2.HTTP信息头管理器,添加Content-Tpe,  application/soap+xml;c ...

  4. [转]C#通过Http发送Soap请求

    /// <summary>        /// 发送SOAP请求,并返回响应xml        /// </summary>        /// <param na ...

  5. webService 发送soap请求,并解析返回的soap报文

    本例应用场景:要做一个webService测试功能,不局限于任何一种固定格式的webService,所以像axis,cxf等框架就不好用了.只有深入到webService的原理,通过发收soap报文, ...

  6. JAVA使用apache http组件发送POST请求

    在上一篇文章中,使用了JDK中原始的HttpURLConnection向指定URL发送POST请求 可以看到编码量有些大,并且使用了输入输出流 传递的参数还是用“name=XXX”这种硬编的字符串进行 ...

  7. java通过java.net.URL发送http请求调用接口

    一般在*.html,*.jsp页面中我们通过使用ajax调用接口,这个是我们通常用的.对于这些接口,大都是本公司写的接口供自己调用,所以直接用ajax就可以.但是,如果是多家公司共同开发一个东西,一个 ...

  8. 【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)

    Java原生的API可用于发送HTTP请求 即java.net.URL.java.net.URLConnection,JDK自带的类: 1.通过统一资源定位器(java.net.URL)获取连接器(j ...

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

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

随机推荐

  1. 章节十一、1-Junit介绍

    一.Junit是一个开源的测试框架,在selenium的jar包中,不需要单独安装和搭建环境 二.@BeforeClass:当在方法上加了这个注解的话,这个方法会在这个类的第一个test方法之前运行. ...

  2. 移动端click延迟和tap事件

    一.click等事件在移动端的延迟 click事件在移动端和pc端均可以触发,但是在移动端有延迟现象. 1.背景 由于早期移动设备浏览网页时内容较小,为了增强用户体验,苹果公司专门为移动设备设计了双击 ...

  3. maven项目更换本地仓库

    由于电脑重装系统更换原来maven项目的本地仓库 以前的仓库位置如图 需要更换的仓库位置 更换步骤如下: 更换后:

  4. Python爬虫【实战篇】scrapy 框架爬取某招聘网存入mongodb

    创建项目 scrapy startproject zhaoping 创建爬虫 cd zhaoping scrapy genspider hr zhaopingwang.com 目录结构 items.p ...

  5. 把流的形式转化为Base64

    public class Test2 { public static String get() throws IOException { InputStream resourceAsStream = ...

  6. 【新特性速递】FineUIPro/Mvc/Core 全新移动端访问体验(示例首页)!

    移动端支持 虽然 FineUIPro 早在 2016 年就已经完成对移动端的适配工作,并新增了 50 多个官网示例. 并且,我们也新增了一个移动端的首页 http://pro.fineui.com/m ...

  7. Mac下开发ASP.NET Core应用,我用FineUICore!

    在 Mac 下开发 ASP.NET Core 2.0+ 应用,我用FineUICore! FineUICore:企业级 ASP.NET 控件库,10年持续更新,只为你来:http://fineui.c ...

  8. python-三级菜单-67

    menu = { '北京': { '海淀': { '五道口': { 'soho': {}, '网易': {}, 'google': {} }, '中关村': { '爱奇艺': {}, '汽车之家': ...

  9. mondb 常用命令学习记录

    mondb 常用命令学习记录 一.MongoDB 下载安装 MongoDB官网 提供了可用于 32 位和 64 位系统的预编译二进制包,你可以从MongoDB官网下载安装,MongoDB 预编译二进制 ...

  10. 安装Cnario提示.Net 3.5安装错误, 检查Windows系统更新提示无法检查到更新, 安装.Net 3.5提示"Windows无法完成请求的更改, 错误代码:0x800F081F"

    症状: Windows检查系统更新时提示无法完成, 尝试安装.Net 3.5等组件时都无法完成, 错误代码: 0x800F081F 原因: 可能时设置了禁止Windows自动更新, 需要重新打开 解决 ...