轉載自:https://blog.csdn.net/qq_41694906/article/details/88029533
目錄
一:WebService的服務端發布
1:發布web程序服務端發布
2:本地發布
二:Webservice客戶端調用:
1:本地生成代碼,直接調用:
2、利用dos命令生成代碼,和第一種基本一致
3:利用apache的AXIS直接調用遠程的web service
4:service編程實現調用
5:HttpURLConnection調用方式
6.Ajax調用方式
Web Service是構建互聯網分布式系統的基本部件,它是一個應用程序,它向外界暴露出一個能夠通過Web進行調用的API。這就是說,別人能夠用編程的方法通過Web來調用這個應用程序。
它通過標准通信協議,在互聯網上以服務的方式發布有用的程序模塊,目前大部分是用SOAP作為通信協議。
它提供一份詳細的接口說明書,來幫助用戶構建應用程序,這個接口說明書叫WSDL(Web服務描述語言,Web Service Description Language)。
請求報文和返回報文都是XML格式的,XML(Extensible Markup Language)即可擴展標記語言,它與HTML一樣,都是SGML(Standard Generalized MarkupLanguage,標准通用標記語言)。
一:WebService的服務端發布
1:發布web程序服務端發布
創建 service 接口
創建接口實現類,實現業務邏輯
配置 web.xml 中 中 Xfire
提供對 xfire 的攔截
配置 webservice 配置
在 class 目錄下建立 META-INF 目錄,如(META-INF>xfire->services.xml),在
services.xml 文件中進行 webservice 服務的發布.
然后啟動服務,在瀏覽器中輸入http://ip/項目名稱/services就可以看到發布的接口了
2:本地發布
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
/**
* Title: ServiceHello
* Description: 基於jdk1.6以上的javax.jws 發布webservice接口
@WebService - 它是一個注解,用在類上指定將此類發布成一個ws。
Endpoint – 此類為端點服務類,它的方法publish用於將一個已經添加了@WebService注解
對象綁定到一個地址的端口上。
* Version:1.0.0
* @author panchengming
*/
@WebService
public class JwsServiceHello {
/** 供客戶端調用方法 該方法是非靜態的,會被發布
* @param name 傳入參數
* @return String 返回結果
* */
public String getValue(String name){
return "歡迎你! "+name;
}
/**
* 方法上加@WebMentod(exclude=true)后,此方法不被發布;
* @param name
* @return
*/
@WebMethod(exclude=true)
public String getHello(String name){
return "你好! "+name;
}
/** 靜態方法不會被發布
* @param name
* @return
*/
public static String getString(String name){
return "再見!"+name;
}
//通過EndPoint(端點服務)發布一個WebService
public static void main(String[] args) {
/*參數:1,本地的服務地址;
2,提供服務的類;
*/
Endpoint.publish("http://192.168.1.105:8080/Service/ServiceHello", new JwsServiceHello());
System.out.println("發布成功!");
//發布成功后 在瀏覽器輸入 http://192.168.1.105:8080/Service/ServiceHello?wsdl
}
}
二:Webservice客戶端調用:
1:本地生成代碼,直接調用:
1:新建一個class類,用於調用webservice。右鍵src,找到Web Service Client,並輸入wsdl地址,選擇下載代碼的路徑;
(url: http://192.168.1.105:8080/Service/ServiceHello?wsdl)
2.將地址上的文件下載下來(注意和發布JDK一致);
3.寫調用方法調用下載下來的WebService中的java類中的方法;
示例:
import com.pcm.ws.jws.JwsServiceHello;
import com.pcm.ws.jws.JwsServiceHelloService;
/**
*
* Title: JwsClientHello
* Description: webService 客戶端調用
* Version:1.0.0
* @author panchengming
*/
public class JwsClientHello {
public static void main(String[] args) {
//調用webservice
JwsServiceHello hello=new JwsServiceHelloService().getJwsServiceHelloPort();
String name=hello.getValue("panchengming");
System.out.println(name);
}
}
2、利用dos命令生成代碼,和第一種基本一致
A、在工作空間創建用於存放使用wsimport命令生成的客戶端代碼的java工程
B、使用jdk提供的wsimport命令生成客戶端代碼
● wsimport命令是jdk提供的,作用是根據使用說明書生成客戶端代碼,wsimport只支持SOAP1.1客戶端的生成
● wsimport常用參數
-d:默認參數,用於生成.class文件
-s:生成.java文件
-p:指定生成java文件的包名,不指定則為WSDL說明書中namespace值得倒寫
C、在doc窗口進入java工程項目的src目錄,執行wsimport命令
D、在Eclipse中刷新java項目,將生成的客戶端代碼copy到客戶端工程中
E、創建服務視圖,類名從<service>標簽的name屬性獲取
F、獲取服務實現類,視圖實例調用getProt()方法,實現類的類名從portType的name屬性獲取
G、調用查詢方法,方法名從portType下的operation標簽的name屬性獲取
package com.webservice.client;
import com.webservice.jaxws.WeatherServiceImpl;
import com.webservice.jaxws.WeatherServiceImplService;
public class Client {
public static void main(String[] args) {
//創建視圖
WeatherServiceImplService wsis = new WeatherServiceImplService();
//獲取服務實現類
WeatherServiceImpl wsi = wsis.getPort(WeatherServiceImpl.class);
//調用查詢方法
String weather = wsi.queryWeather("北京");
System.out.println(weather);
}
}
● <service> 服務視圖,webservice的服務結點,它包括了服務端點
● <binding> 為每個服務端點定義消息格式和協議細節
● <portType> 服務端點,描述 web service可被執行的操作方法,以及相關的消息,通過binding指向portType
● <message> 定義一個操作(方法)的數據參數(可有多個參數)
● <types> 定義 web service 使用的全部數據類型
3:利用apache的AXIS直接調用遠程的web service
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());
}
}
}
4:service編程實現調用
(1)、開發步驟
A、wisimport生成客戶端代碼
B、使用serivce類創建服務視圖
C、獲取服務實現類
D、調用查詢方法
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import cn.itcast.mobile.MobileCodeWSSoap;
/**
*
* <p>Title: ServiceClient.java</p>
* <p>Description:Service編程實現客戶端</p>
*/
public class ServiceClient {
public static void main(String[] args) throws IOException {
//創建WSDL地址,不是服務地址
URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
//創建服務名稱
//1.namespaceURI - 命名空間地址
//2.localPart - 服務名稱
QName qname = new QName("http://WebXml.com.cn/", "MobileCodeWS");
//Service創建視圖
//參數:
//1.wsdlDocumentLocation - 使用說明書地址
//2.serviceName - 服務名稱
Service service = Service.create(url, qname);
//獲取實現類
MobileCodeWSSoap mobileCodeWSSoap = service.getPort(MobileCodeWSSoap.class);
//調用查詢方法
String result = mobileCodeWSSoap.getMobileCodeInfo("188888888", "");
System.out.println(result);
}
}
5:HttpURLConnection調用方式
(1)、開發步驟
A、創建服務地址
B、打開服務地址的一個連接
C、設置連接參數
● 注意
a、POST必須大寫,如果小寫會出如下異常:
b、如果不設置輸入輸出,會報異常
D、組織SOAP協議數據,發送給服務器
E、接收服務端的響應
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* <p>Title: HttpClient.java</p>
* <p>Description:HttpURLConnection調用方式</p>
*/
public class HttpClient {
public static void main(String[] args) throws IOException {
//1:創建服務地址
URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
//2:打開到服務地址的一個連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//3:設置連接參數
//3.1設置發送方式:POST必須大寫
connection.setRequestMethod("POST");
//3.2設置數據格式:Content-type
connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
//3.3設置輸入輸出,新創建的connection默認是沒有讀寫權限的,
connection.setDoInput(true);
connection.setDoOutput(true);
//4:組織SOAP協議數據,發送給服務端
String soapXML = getXML("1866666666");
OutputStream os = connection.getOutputStream();
os.write(soapXML.getBytes());
//5:接收服務端的響應
int responseCode = connection.getResponseCode();
if(200 == responseCode){//表示服務端響應成功
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String temp = null;
while(null != (temp = br.readLine())){
sb.append(temp);
}
System.out.println(sb.toString());
is.close();
isr.close();
br.close();
}
os.close();
}
/**
* <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope 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/">
<soap:Body>
<getMobileCodeInfo xmlns="http://WebXml.com.cn/">
<mobileCode>string</mobileCode>
<userID>string</userID>
</getMobileCodeInfo>
</soap:Body>
</soap:Envelope>
* @param phoneNum
* @return
*/
public static String getXML(String phoneNum){
String soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap:Envelope 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/\">"
+"<soap:Body>"
+"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
+"<mobileCode>"+phoneNum+"</mobileCode>"
+"<userID></userID>"
+"</getMobileCodeInfo>"
+" </soap:Body>"
+"</soap:Envelope>";
return soapXML;
}
}
6.Ajax調用方式
<!doctype html>
<html lang="en">
<head>
<title>Ajax調用方式</title>
<script type="text/javascript">
function queryMobile(){
//創建XMLHttpRequest對象
var xhr = new XMLHttpRequest();
//打開鏈接
xhr.open("post","http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",true);
//設置content-type
xhr.setRequestHeader("content-type","text/xml;charset=utf-8");
//設置回調函數
xhr.onreadystatechange=function(){
//判斷客戶端發送成功&&服務端響應成功
if(4 == xhr.readyState && 200 == xhr.status){
alert(xhr.responseText);
}
}
//組織SOAP協議數據
var soapXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap:Envelope 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/\">"
+"<soap:Body>"
+"<getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"
+"<mobileCode>"+document.getElementById("phoneNum").value+"</mobileCode>"
+"<userID></userID>"
+"</getMobileCodeInfo>"
+" </soap:Body>"
+"</soap:Envelope>";
alert(soapXML);
//發送請求
xhr.send(soapXML);
}
</script>
</head>
<body>
手機號歸屬地查詢:<input type="text" id="phoneNum" /><input type="button" value="查詢" οnclick="javascript:queryMobile();"/>
</body>
</html>
參考文章:https://blog.csdn.net/qq_35124535/article/details/62226585#t2
整理至此,希望對大家有幫助
————————————————
版權聲明:本文為CSDN博主「蒼杲」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_41694906/article/details/88029533