Java Create WebService Client

Source: Internet
Author: User
Tags soap

There are many ways to implement Java WebService, and there are some tools available. This is only a lack of the previous, so that the first to see spring WebService. It took a few days to find and to use the function does not match, ...

The current learning requirement is WebService client. Thus the entire article is used to illustrate the creation of Java WebServiceClient.

First use Java's soapconnection implementation. The first specific client access process is

Soapconnection connection = null;try {soapconnectionfactory sfc = soapconnectionfactory.newinstance (); connection = Sfc.createconnection (); SoapMessage SoapMessage = Objecttosoapxml (object, Nsmethod, Nsname); URL endpoint = new url (new URL (URL), "", New URLStreamHandler () {@Overrideprotected urlconnection openconnection (url url) t Hrows IOException {URL target = new URL (url.tostring ()); URLConnection connection = Target.openconnection ();//Connection Settingsconnection.setconnecttimeout (120000); 2 minconnection.setreadtimeout (60000); 1 Minreturn (connection);}}); SoapMessage response = Connection.call (SoapMessage, endpoint);} catch (Exception e) {}

This one first creates the Soapconnection call method to send a request to the server side, and the two parameters of calling are the message soapmessage that is sent, and the server-side address.

The key here is SoapMessage's encapsulation, which in Java, information is generally stored in the form of objects. The problem is how to encapsulate the object containing the information into SoapMessage. The way I used to be

Private static<t> SoapMessage Objecttosoapxml (T object, String Nsmethod, String nsname) {SoapMessage SoapMessage = n ull;try {messagefactory messagefactory = messagefactory.newinstance (soapconstants.soap_1_1_protocol); soapMessage = Messagefactory.createmessage (); Soappart Soappart = Soapmessage.getsoappart ();//SOAP Envelopesoapenvelope envelope = Soappart.getenvelope (); Envelope.setprefix ("soap-env"); Envelope.addnamespacedeclaration ("ns1", nsmethod);//SOAP Bodysoapbody soapBody = Envelope.getbody (); Soapbody.setprefix ("soap-env"); Soapbody.adddocument (Jaxbobjecttoxml (object, NsMethod, NsName) );//Writes the class in body to Soapmessage.savechanges () in the form of document;} catch (SoapException e) {e.printstacktrace ();} return soapmessage;}

Using Messagefactory to create SoapMessage, here's a little bit to note soapconstants.soap_1_1_protocol, The reason for using this parameter is to specify that the SoapMessage Content-type is Text/xml,charset=utf-8, and the others can refer to other constants. The created SoapMessage contains Soapenvelop, which adds prefixes and namespaces. The next step is to add the information object to be passed in Soapbody. The first examples that you see are the addition of an element to an element. The scalability is too poor. Always consider adding the entire object in. The way of adoption is soapbody adddocument. It is necessary to convert the information object into a Org.w3c.dom.Document object. Next is the conversion method

private static<t> Document jaxbobjecttoxml (T emp, string Nsmethod, String Nsname) {try {jaxbcontext context = Jaxbcontext.newinstance (Emp.getclass ());//Create the Documentdocumentbuilderfactory dbf = documentbuilderfactory.newinstance ();D Ocumentbuilder db = Dbf.newdocumentbuilder ();D ocument Document = db.newdocument ();//Marshal the Object to a documentmarshaller Marshaller = C Ontext.createmarshaller (); Marshaller.marshal (EMP, document); if (null! = document) {Document.renamenode ( Document.getfirstchild (), Nsmethod, nsname);} return document;} catch (Exception e) {logger.error (e.tostring (), e);} return null;} 

Use JAXB to convert an object to the Xml,marshal method to directly implement the objects to document. One of the problems I've encountered here is that when it comes to XML, my XML requires a prefix for the root element. No knowledge is really bad to add. Finally find the implementation way is converted to the document to get the root element, by Getfirstchild, and then rename the root element Renamenode, here is the problem is the last two parameters of this method is a namespace, one is renamed after the node name. I'm going to use a prefix, no namespace. In fact, this is no knowledge. The prefix and namespace should be corresponding, and the namespace and prefix should be set together. Just namespaces are not displayed. If only the prefix is set, no namespace will be an error. The problem here is happily solved, at this time is finished the object encapsulation into SoapMessage, you can through the soapconnection to the service side to send messages.

The message is sent out. Does the server return the results to be processed? Of course, you can get the elements you want through the way the elements are fetched. The same extensibility is too poor. The way I use it is to implement the content of Soapbody in the object.

Public static<t> T Parsesoapmessage (SoapMessage reqmsg, T object, String name) {try {reqmsg = Removeutfbom (reqmsg); S Oapbody soapbody = reqmsg.getsoapbody ();D ocument Document = soapbody.extractcontentasdocument ();// Gets the message body Document.renamenode (document.getfirstchild (), NULL, name) in the return message;//root node minus prefix jaxbcontext JC = Jaxbcontext.newinstance (Object.getclass ()); Unmarshaller Unmarshaller = Jc.createunmarshaller (); object = (T) Unmarshaller.unmarshal (document); catch (Exception e) {logger.error (e.tostring (), e);} return object;}

  

Big problem comes, call soapconnection return SoapMessage, direct call Getsoapbody error. A few times view, is the return result is utf-8 BOM drop, amount, this processing did not find a good way. Eventually it just turns the soapmessage into a string to remove the BOM and convert it back. Because the document was used before the object was converted to SoapMessage, it is now considered and feasible. Then note the extracted document. My side still contains the prefix, so use renamenode do a bit to remove the prefix processing, and then use the Unmarshal to the document hi skin to the object. It's finally done.

The way to the BOM

private static SoapMessage Removeutfbom (SoapMessage soapmessage) {Bytearrayoutputstream BAOs = Null;try{baos = new ByteAr Rayoutputstream (); Soapmessage.writeto (BAOs); String soapstring = baos.tostring (), if (Baos.tostring (). StartsWith ("\ufeff")) {soapstring = soapstring.substring (1); I Nputstream is = new Bytearrayinputstream (Soapstring.getbytes ()); SoapMessage = Messagefactory.newinstance (). CreateMessage (null, is);}} catch (SoapException e) {logger.error (e.tostring (), E),} catch (IOException e) {logger.error (e.tostring (), e);} return soapmessage;}

And finally, there's the definition of the XML counterpart Bean.

The way I take it is to annotate the class

@XmlRootElement (name = "name")//declared as root element, root element name
@XmlAccessorType (Xmlaccesstype.field)

And then on each element,

@XmlElement (name = "ElementName", nillable = True)

Specifies that the property corresponds to the name of the element in the XML, using the Nillable property because if this property is empty, the corresponding XML element does not exist, and if this property is true, the empty property is also displayed.

When there are other objects in the class containing the root element, the other objects are declared in the same way

First declare the @XmlAccessorType on the Class (Xmlaccesstype.field)

@XmlElement declared on the corresponding property (name = "ElementName", nillable = True)

And then some properties are list

@XmlElementWrapper (name= "ListName")
@XmlElement (name= "Listelementname", nillable = True)

wrapper specifies the name of the list, followed by the name of each element in the list.

I'm finally done.

Java Create WebService Client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.