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

目录

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

二、客户端访问webservice

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

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


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

  1、webservice 代码:

复制代码

 1 package com.ls.demo;
 2 
 3 import javax.jws.WebMethod;
 4 import javax.jws.WebService;
 5 import javax.xml.ws.Endpoint;
 6 
 7 
 8 @WebService
 9 public class HelloWorld {
10     @WebMethod
11     public String sayHello(String str){
12         System.out.println("get Message...");
13         String result = "Hello World, "+str;
14         return result;
15     }
16     public static void main(String[] args) {
17         System.out.println("server is running");
18         String address="http://localhost:9000/HelloWorld";
19         Object implementor =new HelloWorld();
20         Endpoint.publish(address, implementor);
21     }
22 
23 }

复制代码

 

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

  

复制代码

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
 3 <!-- Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
 4 <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://demo.ls.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://demo.ls.com/" name="HelloWorldService">
 5     <types>
 6         <xsd:schema>
 7             <xsd:import namespace="http://demo.ls.com/" schemaLocation="http://localhost:9000/HelloWorld?xsd=1"></xsd:import>
 8         </xsd:schema>
 9     </types>
10     <message name="sayHello">
11         <part name="parameters" element="tns:sayHello"></part>
12     </message>
13     <message name="sayHelloResponse">
14         <part name="parameters" element="tns:sayHelloResponse"></part>
15     </message>
16     <portType name="HelloWorld">
17         <operation name="sayHello">
18             <input wsam:Action="http://demo.ls.com/HelloWorld/sayHelloRequest" message="tns:sayHello"></input>
19             <output wsam:Action="http://demo.ls.com/HelloWorld/sayHelloResponse" message="tns:sayHelloResponse"></output>
20         </operation>
21     </portType>
22     <binding name="HelloWorldPortBinding" type="tns:HelloWorld">
23         <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"></soap:binding>
24         <operation name="sayHello">
25             <soap:operation soapAction=""></soap:operation>
26             <input>
27             <soap:body use="literal"></soap:body>
28             </input>
29             <output>
30                 <soap:body use="literal"></soap:body>
31             </output>
32         </operation>
33     </binding>
34     <service name="HelloWorldService">
35         <port name="HelloWorldPort" binding="tns:HelloWorldPortBinding">
36             <soap:address location="http://localhost:9000/HelloWorld"></soap:address>
37         </port>
38     </service>
39 </definitions>

复制代码

 

二、客户端访问webservice

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

  

复制代码

 1 import java.io.BufferedReader;
 2 import java.io.DataOutputStream;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 import org.apache.commons.httpclient.HttpClient;
 9 import org.apache.commons.httpclient.methods.PostMethod;
10 import org.apache.commons.httpclient.methods.RequestEntity;
11 import org.apache.commons.httpclient.methods.StringRequestEntity;
12 import org.apache.commons.io.IOUtils;
13 
14 public class TestHelloWrold {
15     public static void main(String[] args) throws Exception {
16         String wsdl = "http://localhost:9000/HelloWorld?wsdl";
17         int timeout = 10000;
18         StringBuffer sb = new StringBuffer("");
19         sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
20         sb.append("<soap:Envelope "
21                 + "xmlns:api='http://demo.ls.com/' "
22                 + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
23                 + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
24                 + "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
25         sb.append("<soap:Body>");
26         sb.append("<api:sayHello>");
27         sb.append("<arg0>ls</arg0>");
28         sb.append("</api:sayHello>");
29         sb.append("</soap:Body>");
30         sb.append("</soap:Envelope>");
31 
32         
33         
34         // HttpClient发送SOAP请求
35         System.out.println("HttpClient 发送SOAP请求");
36         HttpClient client = new HttpClient();
37         PostMethod postMethod = new PostMethod(wsdl);
38         // 设置连接超时
39         client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
40         // 设置读取时间超时
41         client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
42         // 然后把Soap请求数据添加到PostMethod中
43         RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
44         //设置请求头部,否则可能会报 “no SOAPAction header” 的错误
45         postMethod.setRequestHeader("SOAPAction","");
46         // 设置请求体
47         postMethod.setRequestEntity(requestEntity);
48         int status = client.executeMethod(postMethod);
49         // 打印请求状态码
50         System.out.println("status:" + status);
51         // 获取响应体输入流
52         InputStream is = postMethod.getResponseBodyAsStream();
53         // 获取请求结果字符串
54         String result = IOUtils.toString(is);
55         System.out.println("result: " + result);
56 
57         
58         
59         // HttpURLConnection 发送SOAP请求
60         System.out.println("HttpURLConnection 发送SOAP请求");
61         URL url = new URL(wsdl);
62         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
63 
64         conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
65         conn.setRequestMethod("POST");
66         conn.setUseCaches(false);
67         conn.setDoInput(true);
68         conn.setDoOutput(true);
69         conn.setConnectTimeout(timeout);
70         conn.setReadTimeout(timeout);
71         
72         DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
73         dos.write(sb.toString().getBytes("utf-8"));
74         dos.flush();
75         
76         
77         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
78         String line = null;
79         StringBuffer strBuf = new StringBuffer();
80         while ((line = reader.readLine()) != null) {
81             strBuf.append(line);
82         }
83         dos.close();
84         reader.close();
85         
86         System.out.println(strBuf.toString());
87     }
88 
89 }

复制代码

 

  

 响应报文如下:

  

复制代码

<?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工具

  2、生成客户端代码访问

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

 

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

 

发布了32 篇原创文章 · 获赞 7 · 访问量 4万+
展开阅读全文

java soap发送到webService服务端问题

06-15

问题: 以下这个报错 求大神怎么解决 报错 com.sun.xml.internal.ws.client.ClientTransportException: HTTP 传输错误: java.net.ConnectException: Connection refused: connect at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(HttpClientTransport.java:117) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:208) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:130) at com.sun.xml.internal.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:124) at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:1121) at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:1035) at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:1004) at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:862) at com.sun.xml.internal.ws.client.Stub.process(Stub.java:448) at com.sun.xml.internal.ws.client.dispatch.DispatchImpl.doInvoke(DispatchImpl.java:250) at com.sun.xml.internal.ws.client.dispatch.DispatchImpl.invoke(DispatchImpl.java:289) at com.hzyx.his.test.SoapTest.test2(SoapTest.java:78) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108) at org.testng.internal.Invoker.invokeMethod(Invoker.java:661) at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109) at org.testng.TestRunner.privateRun(TestRunner.java:744) at org.testng.TestRunner.run(TestRunner.java:602) at org.testng.SuiteRunner.runTest(SuiteRunner.java:380) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340) at org.testng.SuiteRunner.run(SuiteRunner.java:289) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301) at org.testng.TestNG.runSuitesLocally(TestNG.java:1226) at org.testng.TestNG.runSuites(TestNG.java:1144) at org.testng.TestNG.run(TestNG.java:1115) at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:432) at sun.net.www.http.HttpClient.openServer(HttpClient.java:527) at sun.net.www.http.HttpClient.<init>(HttpClient.java:211) at sun.net.www.http.HttpClient.New(HttpClient.java:308) at sun.net.www.http.HttpClient.New(HttpClient.java:326) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1202) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1181) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1032) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:966) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1316) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1291) at com.sun.xml.internal.ws.transport.http.client.HttpClientTransport.getOutput(HttpClientTransport.java:104) ... 40 more 源码: //webservice命名空间 String ns = "http://services.agent.sinobest.cn/"; //wsdl地址 String wsdlUrl = "http://localhost:8080/Service?wsdl"; URL url = new URL(wsdlUrl); //创建服务 Webservice类名:Service QName sName = new QName(ns, "Service"); Service service = Service.create(url, sName); // 创建Dispatch对象 通过SOAPMessage 方式 QName qName = new QName(ns, "ServicePort"); Dispatch<SOAPMessage> dispatch = service.createDispatch(new QName(ns, "Service"), SOAPMessage.class, Service.Mode.MESSAGE); // 创建SOAPMessage SOAPMessage msg = MessageFactory.newInstance( SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(); msg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8"); SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope(); // 创建SOAPBody SOAPBody body = envelope.getBody(); //设置参数 QName ename = new QName(ns, "login", "ser"); SOAPBodyElement ele = body.addBodyElement(ename); ele.addChildElement("arg0").setValue("100"); //输出传递参数 msg.writeTo(System.out); // 通过Dispatch传递消息,会返回响应消息 SOAPMessage response = dispatch.invoke(msg); 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览