WebService接口的调用
一、什么是Web Service
Web Service是一个SOA(面向服务的编程)的架构,不需要依赖于语言和平台,就可以实现不同的语言间的相互调用,通过Internet进行基于http协议互相交换数据或集成。
Webservice的一个最基本的目的就是提供在各个不同平台的不同应用系统的协同工作能力。你通过它开放出去你本地的功能,别人通过它就可以调用你本地的功能。
所以只要是能够平台独立,无关语言,无关操作系统,基于XML作为数据交换格式的应用程序都可以叫做Web Service。
记住一句话:WebService是一种跨编程语言和跨操作系统平台的远程调用技术。
跨编程语言和跨操作系统平台:也就是说Asp.net开发的WebService用java代码调用完全没问题,和操作系统也没有关系。
远程调用技术:也就是说网络是通的就能用。
二、Web Service的实现
WebService = WSDL + SOAP + UDDI
-
WSDL (WebServices Description Language)
WSDL文档是一个用于精确描述Web Service的XML文档,用于说明一组 SOAP 消息以及如何交换这些消息。
文档实例:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
详解参考:https://blog.youkuaiyun.com/liuchunming033/article/details/41210151 -
SOAP(Simple Object AccessProtocol)
简单对象访问协议。是用于在应用程序之间进行通信的一种通信协议。SOAP 基于XML 和 HTTP ,其通过XML 来实现消息描述,然后再通过 HTTP 实现消息传输。SOAP是WSDL的通信协议,当用户通过UDDI找到你的WSDL描述文档后,他通过SOAP调用你建立的Web服务中的一个或多个操作。 -
UDDI(Universal Description,Discovery and Integration)
通用的描述,发现以及整合----UDDI 就是一个目录
三、Web Service的案例
1、开发
1)、接口
public interface WebServiceInter {
String sayHello(String name);
int sumMum(int a, int b);
String connectStr(String str1,String str2,int flag);
}
2)、实现类
import dw.health.webservice.WebServiceInter;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
@javax.jws.WebService(serviceName="MyService", targetNamespace="http://service.WebServiceInter.health.dw/")
public class WebServiceImpl implements WebServiceInter {
@WebMethod(operationName="AliassayHello")
@WebResult(name="myReturn")
@Override
public String sayHello(@WebParam(name="name", targetNamespace="http://service.WebServiceInter.health.dw/") String name) {
System.out.println("恭喜你,调用成功!");
String a = "你好" + name;
return a;
}
@WebMethod
@Override
public int sumMum(int a, int b) {
return a + b;
}
@WebMethod(exclude=true)
@Override
public String connectStr(String str1,String str2,int flag){
String resultStr="no str";
if(flag==1){
resultStr=str1+"---"+str2;
}else if(flag==2){
resultStr=str2+"---"+str1;
}
System.out.println(resultStr);
return resultStr;
}
}
3)、发布接口
import dw.health.webservice.service.WebServiceImpl;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import javax.xml.ws.Endpoint;
public class FaBu {
public static void main(String[] args) {
//使用通过JAX-WS提供的Endpoint来发布webservice
String adress = "http://10.1.83.3:8089/JAXWS/WebServiceInter";
Endpoint.publish(adress,new WebServiceImpl());
System.out.println("通过JAX-WS发布成功");
//通过CXF提供的JaxWsServerFactoryBean来发布webservice
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setServiceClass(WebServiceImpl.class);
factory.setAddress("http://10.1.83.3:8090/CXF/WebServiceInter");
Server server = factory.create();
server.start();
System.out.println("通过CXF发布成功");
}
}
4)、测试发布是否成功
浏览器输入上面的发布地址+?wsdl查看。即:http://10.1.83.3:8090/CXF/WebServiceInter?wsdl
2、调用
1)、远程调用
1.1)、直接cxf远程调用
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class CxfWebservice {
public static void main(String[] args) throws Exception {
// 在一个方法中连续调用多次WebService接口,每次调用前需要重置上下文
ClassLoader cl = Thread.currentThread().getContextClassLoader();
JaxWsDynamicClientFactory clientFactory = JaxWsDynamicClientFactory.newInstance();
Client client = clientFactory.createClient("http://10.1.83.3:8090/CXF/WebServiceInter?wsdl");
Object[] result = client.invoke("AliassayHello", "Cqi");
System.out.println(result[0]);
Thread.currentThread().setContextClassLoader(cl);
QName name = new QName("http://service.WebServiceInter.health.dw/", "sumMum");
Client clientB = clientFactory.createClient("http://10.1.83.3:8090/CXF/WebServiceInter?wsdl");
//Object[] resultB = clientB.invoke("sumMum", 13,13);
Object[] resultB = clientB.invoke(name, 13,13);
System.out.println(resultB[0]);
}
}
1.2)、直接axis远程调用
//不通!
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
public class AxisWebservice {
public static void main(String[] args) {
try {
String respond = new String();
String wsdl = "http://10.1.83.3:8089/JAXWS/WebServiceInter?wsdl";
String namespace = "http://service.WebServiceInter.health.dw/";
String method = "AliassayHello";
String requestPara = "Cqi";
Service service = new Service();
Call call = (Call) service.createCall();
// 设置主机地址和端口
call.setTargetEndpointAddress(wsdl);
// 设置要调用的方法
call.setOperationName(new QName(namespace, method));
//call.setOperationName(method);
// 该方法需要的参数
call.addParameter(new QName(namespace, "name"), XMLType.XSD_STRING, ParameterMode.IN);// 接口的参数
//call.addParameter("name", XMLType.XSD_STRING, ParameterMode.IN);// 接口的参数
// 方法的返回值类型
call.setReturnType(XMLType.XSD_STRING);
// 给方法传递参数,并且调用该方法
call.setUseSOAPAction(true);
call.setSOAPActionURI(namespace + method);
respond = (String)call.invoke(new Object[] { requestPara });
System.out.println("result is: " + respond);
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
2)、转成本地类调用
3)、HttpURLConnection调用
原始js,访问WebService会存在跨域无法访问的问题,可以使用ajax请求一个Servlet,在Servlet使用HttpURLConnection放问WebService,解决ajax直接访问WebService带来的跨域问题。
public static String postRequest(String urlString ,String reqString) {
StringBuffer sb = new StringBuffer("");
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(reqString.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
String lines;
while ((lines = reader.readLine()) != null) {
sb.append(lines);
}
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (sb.toString().length()==0|sb.toString().trim().length()==0) {
return "";
}
return sb.toString();
}
public static void main( String[] args ){
String url="http://10.1.83.3:8090/CXF/WebServiceInter";
//para来自SoapUI测试工具
String para =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.WebServiceInter.health.dw/\">"
+"<soapenv:Header/>"
+"<soapenv:Body>"
+"<ser:AliassayHello>"
+" <!--Optional:-->"
+" <ser:name>Cqi</ser:name>"
+" </ser:AliassayHello>"
+" </soapenv:Body>"
+"</soapenv:Envelope>";
String re= postRequest(url,para);
System.out.println(re);
//结果:<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:AliassayHelloResponse xmlns:ns2="http://service.WebServiceInter.health.dw/"><myReturn>你好Cqi</myReturn></ns2:AliassayHelloResponse></soap:Body></soap:Envelope>
}
8213

被折叠的 条评论
为什么被折叠?



