Полный пример JAX-WS на основе SOAP, показывающий, как использовать механизм оптимизации передачи сообщений (MTOM) и XML-двоичную оптимизированную упаковку (XOP) для отправки двоичного вложения (изображения) с сервера на клиент и наоборот. ,
Включение MTOM на сервере
Разрешить серверу отправлять вложения через MTOM очень просто, просто аннотируйте класс реализации веб-службы с помощью javax.xml.ws.soap.MTOM.
1. Конечная точка веб-службы
Вот веб-сервис в стиле RPC, опубликованный двумя методами,
downloadImage (имя строки)
и
uploadImage (данные изображения)
, чтобы позволить пользователю загружать или загружать файл изображения.
File: ImageServer.java
package com.mkyong.ws;
import java.awt.Image;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface ImageServer{
//download a image from server
@WebMethod Image downloadImage(String name);
//update image to server
@WebMethod String uploadImage(Image data);
}
File: ImageServerImpl.java
package com.mkyong.ws;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;
//Service Implementation Bean
@MTOM
@WebService(endpointInterface = "com.mkyong.ws.ImageServer")
public class ImageServerImpl implements ImageServer{
@Override
public Image downloadImage(String name) {
try {
File image = new File("c:\\images\\" + name);
return ImageIO.read(image);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
public String uploadImage(Image data) {
if(data!=null){
//store somewhere
return "Upload Successful";
}
throw new WebServiceException("Upload Failed!");
}
}
File: ImagePublisher.java
package com.mkyong.endpoint;
import javax.xml.ws.Endpoint;
import com.mkyong.ws.ImageServerImpl;
//Endpoint publisher
public class ImagePublisher{
public static void main(String[]args) {
Endpoint.publish("http://localhost:9999/ws/image", new ImageServerImpl());
System.out.println("Server is published!");
}
}
2. Клиент WebService
Вот клиент веб-сервиса для доступа к опубликованному веб-сервису по URL «http://localhost: 9999/ws/image__«
File: ImageClient.java
package com.mkyong.client;
import java.awt.Image;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;
import com.mkyong.ws.ImageServer;
public class ImageClient{
public static void main(String[]args) throws Exception {
URL url = new URL("http://localhost:9999/ws/image?wsdl");
QName qname = new QName("http://ws.mkyong.com/", "ImageServerImplService");
Service service = Service.create(url, qname);
ImageServer imageServer = service.getPort(ImageServer.class);
/** ** ** ** ** ** ** ** ** ** ** ** test download ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** / Image image = imageServer.downloadImage("rss.png");
//display it in frame
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
System.out.println("imageServer.downloadImage() : Download Successful!");
}
}
3. HTTP и SOAP трафик
Вот трафик HTTP и SOAP, сгенерированный клиентом, захваченный инструментом мониторинга трафика.
P.S Первый запрос wsdl опущен для экономии места . + Клиентский запрос на отправку:
POST/ws/image HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, ** ; q=.2, ** /** ; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0__13
Host: localhost:9999
Connection: keep-alive
Content-Length: 209
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:downloadImage xmlns:ns2="http://ws.mkyong.com/">
<arg0>rss.png</arg0>
</ns2:downloadImage>
</S:Body>
</S:Envelope>
-
Сервер отправляет ответ: **
HTTP/1.1 200 OK Transfer-encoding: chunked Content-type: multipart/related; start="<rootpart** [email protected]>"; type="application/xop+xml"; boundary="uuid:c73c9ce8-6e02-40ce-9f68-064e18843428"; start-info="text/xml" --uuid:c73c9ce8-6e02-40ce-9f68-064e18843428 Content-Id: <rootpart** [email protected]> Тип контента: application/xop xml; charset = utf-8; type = "text/xml" Content-Transfer -Кодирование: двоичное <? xml version = "1.0"?> <S: Конверт xmlns: S = "http://schemas.xmlsoap.org/soap/envelope/"> <S: Body> <ns2: downloadImageResponse xmlns: ns2 = "http://ws.mkyong.com/"> <Возвращение> <xop: Включить xmlns: xop = "http://www.w3.org/2004/08/xop/include" HREF = "чид: [email protected]"> </ХОР: Включить> </Вернуться> </Ns2: downloadImageResponse> </S: Body> </S: Envelope> --uuid: c73c9ce8-6e02-40ce-9f68-064e18843428 Content-Id: <[email protected]> Тип контента: изображение/PNG Content-Transfer-Encoding: двоичный Двоичные данные здесь .............
Включение MTOM на клиенте
Чтобы клиент мог отправлять вложения через MTOM на сервер, требуются дополнительные усилия, см. Следующий пример:
….//codes enable MTOM in client BindingProvider bp = (BindingProvider) imageServer; SOAPBinding binding = (SOAPBinding) bp.getBinding(); binding.setMTOMEnabled(true);
=== 1. Клиент WebService Вот клиент веб-сервиса для отправки файла изображения на опубликованную конечную точку выше (http://localhost: 8888/ws/image) через MTOM __File: ImageClient.java__
package com.mkyong.client;
import java.awt.Image; import java.io.File; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.soap.MTOMFeature; import javax.xml.ws.soap.SOAPBinding;
import com.mkyong.ws.ImageServer;
public class ImageClient{
public static void main(String[]args) throws Exception {
URL url = new URL("http://localhost:8888/ws/image?wsdl");
QName qname = new QName("http://ws.mkyong.com/", "ImageServerImplService");
Service service = Service.create(url, qname); ImageServer imageServer = service.getPort(ImageServer.class);
/** ** ** ** ** ** ** ** ** ** ** ** test upload ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** / Image imgUpload = ImageIO.read(new File("c:\\images\\rss.png"));
//enable MTOM in client BindingProvider bp = (BindingProvider) imageServer; SOAPBinding binding = (SOAPBinding) bp.getBinding(); binding.setMTOMEnabled(true);
String status = imageServer.uploadImage(imgUpload);
System.out.println("imageServer.uploadImage() : " + status);
}
}
=== 2. HTTP и SOAP трафик Вот трафик HTTP и SOAP, сгенерированный клиентом, захваченный инструментом мониторинга трафика. __P.S Первый запрос wsdl опущен для экономии места .__ + ** Клиентский запрос на отправку: **
POST/ws/image HTTP/1.1 Content-type: multipart/related; start="<rootpart** [email protected] >"; type="application/xop+xml"; boundary="uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931";
start-info="text/xml" Soapaction: "" Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, ; q=.2, /** ; q=.2 User-Agent: JAX-WS RI 2.1.6 in JDK 6 Host: localhost:9999 Connection: keep-alive Content-Length: 6016
--uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931
Content-Id: <rootpart** [email protected] > Content-Type: application/xop xml; charset = utf-8; type = "text/xml" Content-Transfer -Кодирование: двоичное
<? xml version = "1.0"?> <S: Конверт xmlns: S = "http://schemas.xmlsoap.org/soap/envelope/"> <S: Body> <ns2: uploadImage xmlns: ns2 = "http ://ws.mkyong.com/"> <arg0> <xop: Включить xmlns: xop =" http://www.w3.org/2004/08/xop/include "href =" cid: 2806f201-e15e- [email protected] "> </xop: Include> </arg0> </ns2: uploadImage> </S: Body> </S: Envelope>
--uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931 Content-Id: < [email protected] > Content-Type: image/png Content-Transfer-Encoding: binary
Binary data here………….
** Сервер отправляет ответ: **
HTTP/1.1 200 OK Transfer-encoding: chunked Content-type: multipart/related; start="<rootpart** [email protected] >"; type="application/xop+xml"; boundary="uuid:188a5835-198b-4c28-9b36-bf030578f2bd"; start-info="text/xml"
--uuid:188a5835-198b-4c28-9b36-bf030578f2bd
Content-Id: <rootpart** [email protected] > Тип контента: application/xop xml; charset = utf-8; type = "text/xml" Content-Transfer -Кодирование: двоичное
<? xml version = "1.0"?> <S: Envelope xmlns: S = "http://schemas.xmlsoap.org/soap/envelope/"> <S: Body> <ns2: uploadImageResponse xmlns: ns2 = "http ://ws.mkyong.com/"> <return> Загрузка успешно завершена </return> </ns2: uploadImageResponse> </S: Body> </S: Конверт>
--uuid:188a5835-198b-4c28-9b36-bf030578f2bd--
=== Полный документ WSDL Для тех, кто заинтересован в изучении файла WSDL, вы можете получить файл wsdl по URL: __http://localhost: 9999/ws/image? Wsdl__ __ Образец файла ImageServer WSDL__
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://ws.mkyong.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://ws.mkyong.com/" name="ImageServerImplService">
<types></types>
<message name="downloadImage"> <part name="arg0" type="xsd:string"></part> </message> <message name="downloadImageResponse"> <part name="return" type="xsd:base64Binary"></part> </message>
<message name="uploadImage"> <part name="arg0" type="xsd:base64Binary"></part> </message> <message name="uploadImageResponse"> <part name="return" type="xsd:string"></part> </message>
<portType name="ImageServer">
<operation name="downloadImage">
<input message="tns:downloadImage"></input>
<output message="tns:downloadImageResponse"></output>
</operation>
<operation name="uploadImage">
<input message="tns:uploadImage"></input>
<output message="tns:uploadImageResponse"></output>
</operation>
</portType>
<binding name="ImageServerImplPortBinding" type="tns:ImageServer"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"> </soap:binding>
<operation name="downloadImage">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
</output>
</operation>
<operation name="uploadImage">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://ws.mkyong.com/">
</soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://ws.mkyong.com/">
</soap:body>
</output>
</operation>
</binding>
<service name="ImageServerImplService"> <port name="ImageServerImplPort" binding="tns:ImageServerImplPortBinding"> <soap:address location="http://localhost:9999/ws/image"></soap:address> </port> </service> </definitions>
=== Скачать исходный код Загрузить его - ссылка://wp-content/uploads/2010/11/JAX-WS-Attachment-MTOM-Example.zip[JAX-WS-Attachment-MTOM-Example.zip](20 КБ) [#reference]## === Ссылка , http://www.devx.com/xml/Article/34797/1763/page/1 , http://download.oracle.com/docs/cd/E17802__01/webservices/webservices/docs/2.0/jaxws/mtom-swaref.html , http://www.crosschecknet.com/intro__to__mtom.php , http://download.oracle.com/docs/cd/E12840__01/wls/docs103/webserv__adv/mtom.html , http://www.theserverside.com/news/1363957/Sending-Attachments-with-SOAP , http://metro.java.net/guide/Binary__Attachments____MTOM__.html ссылка://тег/вложение/[вложение]ссылка://тег/jax-ws/[jax-ws]ссылка://тег/мтом/[мтом]ссылка://тег/веб-сервисы/[веб-сервисы]