原文地址:https://blog.csdn.net/linjinhuo/article/details/78777694
文章目錄
一、發布一個webservice服務(jdk原生)
1.編寫服務接口
2.服務實現類
3.發布服務
4.瀏覽器查看是否發布成功
二、幾種客戶端調用方式
1、jdk原生調用(需要獲取服務接口文件)
2、用import命令生成客戶端代碼
3、cxf類庫 兩種調用方式。
4、axis調用方式
5、httpClient調用方式。
6、SoapUI
7、其他
一、發布一個webservice服務(jdk原生)
1.編寫服務接口
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
*
* 基於soap協議(http+xml)的服務
*/
@WebService(name = "Login",// 定義Port名稱
serviceName = "MyService", // 修改WebService服務名稱
targetNamespace = "http://com.soft.ws/my" // 定義命名空間,默認為倒置的包名
)
public interface MyService {
// 提供一個對外公開的服務
@WebMethod(operationName = "authorization")
// 修改方法名
String authorization(@WebParam(name = "userId") String userId,
@WebParam(name = "password") String password);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2.服務實現類
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
* 服務實現類
*/
@WebService(endpointInterface = "com.soft.platform.webservice.server.MyService",
name = "Login",// 定義Port名稱
serviceName = "MyService", // 修改WebService服務名稱
targetNamespace = "http://com.soft.ws/my" // 定義命名空間,默認為倒置的包名
//服務實現類和接口的注解要一樣全
)
public class MyServiceImpl implements MyService {
@WebMethod(operationName = "authorization" // 修改方法名
)
@Override
public String authorization(
@WebParam(name = "userId") String userId,
@WebParam(name = "password") String password) {
if ("admin".equals(userId) && "123456".equals(password)) {
return "success";
}
return "error";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
3.發布服務
運行下面的代碼 發布WebService服務
/**
* 發布服務
*
*/
public class MyPublisher {
public static void main(String[] args) {
//指定服務url
String url = "http://192.168.0.101:8089/myservice";
//指定服務實現類
MyService server = new MyServiceImpl();
//采用命令行發布者Endpoint發布服務
Endpoint.publish(url, server);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
4.瀏覽器查看是否發布成功
打開瀏覽器地址欄輸入:http://192.168.0.101:8089/myservice?wsdl
結果如下:
二、幾種客戶端調用方式
上面發布的服務不要關閉,編寫另外一個客戶端類來調用上面發布服務,有以下幾種方法來調用服務
1、jdk原生調用(需要獲取服務接口文件)
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.soft.platform.webservice.server.MyService;
public class WsClient {
public static void main(String[] args) throws Exception {
URL url = new URL("http://192.168.0.101:8089/myservice?wsdl");
// 指定命名空間和服務名稱
QName qName = new QName("http://com.soft.ws/my", "MyService");
Service service = Service.create(url, qName);
// 通過getPort方法返回指定接口
MyService myServer = service.getPort(new QName("http://com.soft.ws/my",
"LoginPort"), MyService.class);
// 調用方法 獲取返回值
String result = myServer.authorization("admin", "123456");
System.out.println(result);
}
}
返回結果: success
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2、用import命令生成客戶端代碼
wsimport -d d:/webservice -keep -p com.soft.test.wsimportClient -verbose http://192.168.0.101:8089/myservice?wsdl
public static void main(String[] args) {
MyService_Service service = new MyService_Service();
MyService login = service.getLoginPort();
String result = login.authorization("admin", "123456");
System.out.println(result);
}
1
2
3
4
5
6
3、cxf類庫 兩種調用方式。
Apache CXF 是開源的WebService框架,CXF幫助您使用前端編程api(如JAX-WS和JAX-RS)構建和開發服務。這些服務可以使用多種協議,如SOAP、XML/HTTP、RESTful HTTP或CORBA,並在多種傳輸協議(如HTTP、JMS或JBI)上工作。
官網地址:http://cxf.apache.org/
public static void main(String[] args) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(MyService.class);
factory.setAddress("http://192.168.0.101:8089/myservice?wsdl");
// 需要服務接口文件
MyService client = (MyService) factory.create();
String result = client.authorization("admin", "123456");
System.out.println(result);
}
1
2
3
4
5
6
7
8
9
public static void main(String[] args) throws Exception {
//采用動態工廠方式 不需要指定服務接口
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf
.createClient("http://192.168.0.101:8089/myservice?wsdl");
QName qName = new QName("http://com.soft.ws/my", "authorization");
Object[] result = client.invoke(qName,
new Object[] { "admin", "123456" });
System.out.println(result[0]);
}
1
2
3
4
5
6
7
8
9
10
4、axis調用方式
這個例子是比較老的axis版本作為客戶端了,最新版官網
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
public class WsAClient {
/**
* 跨平台調用Web Service出現
* faultString: 服務器未能識別 HTTP 頭 SOAPAction 的值:
* JAX-WS規范不需要SoapAction,但是.NET需要,所以產生了這個錯誤。
* options.setAction("目標的TargetNameSpace"+"調用的方法名");
*/
public static void main(String[] args) {
String url = "http://192.168.0.101:8089/myservice?wsdl";
Service service = new Service();
try {
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(url));
// WSDL里面描述的接口名稱(要調用的方法)
call.setOperationName(new QName("http://com.soft.ws/my",
"authorization"));
//跨平台調用加上這個
call.setUseSOAPAction(true);
call.setSOAPActionURI("http://com.soft.ws/my/authorization");
// 接口方法的參數名, 參數類型,參數模式 IN(輸入), OUT(輸出) or INOUT(輸入輸出)
call.addParameter("userId", XMLType.XSD_STRING, ParameterMode.IN);
call.addParameter("password", XMLType.XSD_STRING, ParameterMode.IN);
// 設置被調用方法的返回值類型
call.setReturnType(XMLType.XSD_STRING);
// 設置方法中參數的值
Object result = call.invoke(new Object[] { "admin", "123456" });
System.out.println(result.toString());
} catch (ServiceException | RemoteException | MalformedURLException e) {
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
axis方式依賴的相關jar包如下:
5、httpClient調用方式。
(1)maven依賴如下
<properties>
<httpclient.version>4.5.6</httpclient.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
(2)httpclient作為客戶端調用webservice。代碼如下
/*
* Copyright (c)
*/
package test;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
/**
* webservice客戶端
*
* @author David Lin
* @version: 1.0
* @date 2018-09-09 12:16
*/
public class SoapClient {
public static void main(String args[]) throws Exception {
//soap服務地址
String url = "http://localhost:8888/ssm/Services/UserService?wsdl";
StringBuilder soapBuilder = new StringBuilder(64);
soapBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
soapBuilder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.soft.com/\">");
soapBuilder.append(" <soapenv:Header/>");
soapBuilder.append(" <soapenv:Body>");
soapBuilder.append(" <web:authorization>");
soapBuilder.append(" <userId>").append("admin").append("</userId>");
soapBuilder.append(" <password>").append("123456").append("</password>");
soapBuilder.append(" </web:authorization>");
soapBuilder.append(" </soapenv:Body>");
soapBuilder.append("</soapenv:Envelope>");
//創建httpcleint對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建http Post請求
HttpPost httpPost = new HttpPost(url);
// 構建請求配置信息
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 創建連接的最長時間
.setConnectionRequestTimeout(500) // 從連接池中獲取到連接的最長時間
.setSocketTimeout(3 * 1000) // 數據傳輸的最長時間10s
.build();
httpPost.setConfig(config);
CloseableHttpResponse response = null;
try {
//采用SOAP1.1調用服務端,這種方式能調用服務端為soap1.1和soap1.2的服務
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
//采用SOAP1.2調用服務端,這種方式只能調用服務端為soap1.2的服務
// httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
StringEntity stringEntity = new StringEntity(soapBuilder.toString(), Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
// 判斷返回狀態是否為200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
} else {
System.out.println("調用失敗!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
返回結果為:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:authorizationResponse xmlns:ns2="http://webservice.soft.com/">
<return>success</return>
</ns2:authorizationResponse>
</soap:Body>
</soap:Envelope>
1
2
3
4
5
6
7
8
(3)用Jsoup提取響應數據。
maven依賴
<properties>
<jsoup.version>1.11.3</jsoup.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
</dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
代碼如下:
Document soapRes = Jsoup.parse(content);
Elements returnEle = soapRes.getElementsByTag("return");
System.out.println("調用結果為:"+returnEle.text());
1
2
3
4
6、SoapUI
soapUI是一個開源測試工具,通過soap/http來檢查、調用、實現Web Service的功能/負載/符合性測試。
用這個圖形化工具也可以調用WebService服務,作為測試使用。
7、其他
只要WSDL服務地址能夠訪問,就能根據wsdl描述的信息手動造一個 服務接口文件 ,這樣客戶端就可以使用這個接口文件調用服務。
————————————————
版權聲明:本文為CSDN博主「少年夢fire」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/linjinhuo/java/article/details/78777694