webservicejava实例
A. java怎样提供webservice接口
Java通过WSDL文件来调用webservice:
注意,以下的代码并没有经悄扮过真正的测试,只是说明肢运禅这些情况,不同版本的Axis相差很大,大家最好以apache网站上的例子为准,这里仅仅用于说明其基本用法。
1,直接AXIS调用远程的web service
这种方法比较适合那些高手,他们能直接看懂XML格式的WSDL文件,我自己是看不懂的,尤其我不是专门搞这行的,即使一段时间看懂,后来也就忘记了。历尘直接调用模式如下:
import java.util.Date;
import java.text.DateFormat;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
import java.lang.Integer;
import javax.xml.rpc.ParameterMode;
public class caClient {
public static void main(String[] args) {
try {
String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";
//直接引用远程的wsdl文件
//以下都是套路
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(endpoint);
call.setOperationName("addUser");//WSDL里面描述的接口名称
call.addParameter("userName", org.apache.axis.encoding.XMLType.XSD_DATE,
javax.xml.rpc.ParameterMode.IN);//接口的参数
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//设置返回类型
String temp = "测试人员";
String result = (String)call.invoke(new Object[]{temp});
//给方法传递参数,并且调用方法
System.out.println("result is "+result);
}
catch (Exception e) {
System.err.println(e.toString());
}
}
}
2,直接SOAP调用远程的webservice
这种模式我从来没有见过,也没有试过,但是网络上有人贴出来,我也转过来
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
import java.io.*;
import java.net.*;
import java.util.Vector;
public class caService{
public static String getService(String user) {
URL url = null;
try {
url=new URL("http://192.168.0.100:8080/ca3/services/caSynrochnized");
} catch (MalformedURLException mue) {
return mue.getMessage();
}
// This is the main SOAP object
Call soapCall = new Call();
// Use SOAP encoding
soapCall.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
// This is the remote object we're asking for the price
soapCall.setTargetObjectURI("urn:xmethods-caSynrochnized");
// This is the name of the method on the above object
soapCall.setMethodName("getUser");
// We need to send the ISBN number as an input parameter to the method
Vector soapParams = new Vector();
// name, type, value, encoding style
Parameter isbnParam = new Parameter("userName", String.class, user, null);
soapParams.addElement(isbnParam);
soapCall.setParams(soapParams);
try {
// Invoke the remote method on the object
Response soapResponse = soapCall.invoke(url,"");
// Check to see if there is an error, return "N/A"
if (soapResponse.generatedFault()) {
Fault fault = soapResponse.getFault();
String f = fault.getFaultString();
return f;
} else {
// read result
Parameter soapResult = soapResponse.getReturnValue ();
// get a string from the result
return soapResult.getValue().toString();
}
} catch (SOAPException se) {
return se.getMessage();
}
}
}
3,使用wsdl2java把WSDL文件转成本地类,然后像本地类一样使用,即可。
这是像我这种懒人最喜欢的方式,仍然以前面的global weather report为例。
首先 java org.apache.axis.wsdl.WSDL2Java http://www.webservicex.net/globalweather.asmx.WSDL
原本的网址是http://www.webservicex.net/globalweather.asmx?WSDL,中间个各问号,但是Linux下面它不能解析,所以去掉问号,改为点号。
那么就会出现4个文件:
GlobalWeather.java GlobalWeatherLocator.java GlobalWeatherSoap.java GlobalWeatherSoapStub.java
其中GlobalWeatherSoap.java是我们最为关心的接口文件,如果你对RMI等SOAP实现的具体细节不感兴趣,那么你只需要看接口文件即可,在使用的时候,引入这个接口即可,就好像使用本地类一样。
B. java调用webservice例子
现在大多数项目都会用到spring,所以选择 CXF 框架,cxf能很好的和spring结合
在官网下载最新版 xcf 3.0.3 网站 http://cxf.apache.org/
MyEclipse项目结构图
结构图中各个文件源码
HelloWorldImpl.java
---------
import javax.jws.WebService;
@WebService(endpointInterface = "IHelloWorld", serviceName = "HelloWorld")
public class HelloWorldImpl implements IHelloWorld {
@Override
public String sayHello(String text) {
return "serviceSay: " + text;
}
}
------------------------------------------------------------------------------------------------
IHelloWorld.java
---------
import javax.jws.WebService;
@WebService
public interface IHelloWorld {
public String sayHello(String text);
}
------------------------------------------------------------------------------------------------
Test.java
---------
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.dynamic.DynamicClientFactory;
public class Test {
public static void main(String[] args) throws Exception {
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client c = dcf.createClient("http://localhost:8080/cxf/ws/hwUrl?wsdl");
Object[] param = new Object[] { "----test....." };
Object[] result = c.invoke("sayHello", param);
System.out.println(result[0].toString());
}
}
------------------------------------------------------------------------------------------------
cxf-servlet.xml
-----------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:soap="http://cxf.apache.org/bindings/soap"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:server id="hwService" serviceClass="IHelloWorld"
address="/hwUrl">
<jaxws:serviceBean>
<bean class="HelloWorldImpl" />
</jaxws:serviceBean>
</jaxws:server>
</beans>
------------------------------------------------------------------------------------------------
web.xml
---------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>cxfS</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxfS</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
</web-app>
------------------------------------------------------------------------------------------------
部署项目,然后运行Test.java
在浏览器里面输入http://localhost:8080/cxf/ws/hwUrl?wsdl 可查看webservice服务接口信息
C. 用java怎么写webservice
Web Services以XML作为数据交换的标准格式,它是跨平台的应用,允许以任何方式创建Web Services,在.NET、Java平台上访问。
在Java平台创建和访问Web Service多通过Axis完成。Axis本质上就是一个SOAP引擎,提供创建服务器端、客户端和网关SOAP操作的基本框架。Axis目前版本是为Java编写的。在使用Axis访问Web Service时,需要引入以下包(10个):axis-ant.jar、axis.jar、commons-discovery-0.2.jar、commons-logging-1.0.4.jar、jaxrpc.jar、log4j-1.2.8.jar、saaj.jar、wsdl4j-1.5.1.jar、activation-1.1.jar和mail-1.4.jar。
(1)访问Java创建的Web Service
在当前Java客户端应用中添加相应的10个Axis包,编写客户端程序:
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class Test {
public static void main(String[] args) throws Exception {
try{
String endpoint = "http://localhost:8080/MyService/services/Hello";
Service service = new Service();
Call call = (Call)service.createCall();
call.setTargetEndpointAddress(new java.net.URL(endpoint));
call.setOperationName("getHello");
String res = (String) call.invoke(new Object[]{});
System.out.println(res);
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
其中两处代码加粗,第一处表示引用Java Web Service的URL,第二处表示公共的方法名称。
D. java如何写webservice服务端
Java 中的 Web Service 分为基于 SOAP 的和基于 REST 的两种,下面简单说一个基于 SOAP 的例子。要使用 JDK6u4 之后的版本才能编译通过。
先编写一个 Web Service 的接口:
@WebService
@SOAPBinding(style=Style.RPC)
publicinterfaceTimeServer{
@();
@WebMethodlonggetTimeAsElapsed();
}
再编写 Web Service 实现:
importjava.util.Date;
importjavax.jws.WebService;
@WebService(endpointInterface="test.TimeServer")
{
publicStringgetTimeAsString(){returnnewDate().toString();}
publiclonggetTimeAsElapsed(){returnnewDate().getTime();}
}
最后启动 Web Service:
{
publicstaticvoidmain(String[]args){
Endpoint.publish("http://127.0.0.1:9876/ts",newTimeServerImpl());
}
}
如果正常启动,可以用浏览器访问 http://127.0.0.1:9876/ts?wsdl 看到这个 Web Service 的 wsdl 文档。