Java sends a SOAP request to invoke WebService, parsing the SOAP message __java

Source: Internet
Author: User
Tags base64 cdata decrypt soap uuid xpath soapui stringbuffer

Record Test Code

SOAPUI Call Path

http://localhost:8082/*/webservices/**service?wsdl
Import Org.apache.commons.lang.StringUtils;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;

Import Org.dom4j.xpath.DefaultXPath;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
Import java.util.Base64;
Import java.util.Collections;

Import java.util.List;
    /** * Simulate SOAPUI call WebService, parse return message * Created by Penghongfu 2018-04-26 15:36/public class Testsoap {//test environment address

    public static String Invoice_ws_url = "Http://localhost:8082/*/webservices/**service";
        public static void Main (string[] args) throws Exception {String sid = "Sid value";
        String content = "message contents, josn format";
        String transeq = "UUID";
        String tranreqdate = "2018-04-24";

        StringBuffer stringbuffer = testwebservice (SID, Content, Transeq, tranreqdate); Print HTTP response Data SYstem.out.println (StringBuffer);
        Processing return data String Xmlresult = stringbuffer.tostring (). Replace ("&lt;", "<"); String rtncode = Getxmlmessagebyname (Xmlresult, "Rtncode");/message return status code, 0 indicates normal, 3 is error String message = Getxmlmessagebyn Ame (Xmlresult, "message");/return information, mainly when the status code is not normal, throw String BODY = Getxmlmessagebyname (Xmlresult, "bodies");
                64 decryption if ("0". Equals (Rtncode)) {//Query Success if (Stringutils.isnotblank (body)) {
                Decrypt Base64 encrypted data base64.decoder Decoder = Base64.getdecoder ();
                byte[] Encodedtext = Body.getbytes ();
                String decrypt = new String (Decoder.decode (Encodedtext), "UTF-8");
            System.out.println (decrypt); } else {//query failed}//Invoke WS private static StringBuffer TestWebService (String s ID, string content, String transeq, String tranreqdate) throws Exception {//Stitching request message STring sendmsg = appendxmlcontext (SID, Content, Transeq, tranreqdate);
        Open http connection ַinputstreamreader ISR = null;
        BufferedReader inreader = null;
        StringBuffer result = null;
        OutputStream outobject = null;
            try {URL url = new URL (invoice_ws_url);

            HttpURLConnection httpconn = (httpurlconnection) url.openconnection (); Set HTTP request-related information Httpconn.setrequestproperty ("Content-length", String.valueof (Sendmsg.getby
            TES (). length)); Httpconn.setrequestproperty ("Content-type", "text/xml;
            Charset=utf-8 ");
            Httpconn.setrequestmethod ("POST");
            Httpconn.setdooutput (TRUE);

            Httpconn.setdoinput (TRUE);
            HTTP request Outobject = Httpconn.getoutputstream ();

            Outobject.write (Sendmsg.getbytes ()); If!= (Httpconn.getresponsecode ()) {throw new Exception ("HTTP Request is not success, ResPonse code is "+ Httpconn.getresponsecode ()); }//Get HTTP response Data ISR = new InputStreamReader (Httpconn.getinputstream (), Utf-8
            ");
            Inreader = new BufferedReader (ISR);
            result = new StringBuffer ();
            String Inputline;
            while ((Inputline = Inreader.readline ())!= null) {result.append (inputline);

        return result;
        catch (IOException e) {throw e;
            Finally {//close the input stream if (Inreader!= null) {inreader.close ();
            } if (ISR!= null) {isr.close ();
            //Turn off output stream if (outobject!= null) {outobject.close (); }}//stitching request message private static string Appendxmlcontext (string sid, String content, String transeq, St Ring tranreqdate) {//Build request message StringBuffer STRINGBUffer = new StringBuffer ("<?xml version=\" 1.0\ "encoding=\" utf-8\ "+" >\n <soapenv:envelope
                S:soapenv=\ "http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\ "http://com.foresee.top.service/\" >\n "+ "<soapenv:body>\n" + "<ns1:doservice xmlns:ns1=\" Http://cn.gov.chinatax.gt3nf.nfzcpt.s Ervice/\ ">\n" + "<reqxml><! [Cdata[<?xml version=\ "1.0\" encoding=\ "utf-8\" ">\n" + "<tirippackage xmlns:xsi=\" http://www.w3.o
                Rg/2001/xmlschema\ "version=\" 1.0\ "xsi:type=\" tirippackage\ ">\n" + "<sessionid/>\n" +    "<service>\n" + "<sid>" + Sid + "</sid>\n" + "
                <version>1.0</version>\n "+" <transeq>+ "+ transeq +" </transeq>\n "+
       "<tranReqDate>" + tranreqdate + "</tranreqdate>\n" +         "</service>\n" + "<bizcontent>\n" + "<content>" + Conte
                NT + "</content>\n" + "<paramlist>\n" + "<param>\n" +
                "<name>doctype</name>\n" + "<value>json</value>\n" + "</param>\n" + "<param>\n" + "<name>class name</name>\n "+" <value>ggg</value>\n "+" </param>\ N "+" </paramlist>\n "+" </bizcontent>\n "+" </tiripp
                ackage>\n "+"]]></reqxml>\n "+" </ns1:doservice>\n "+
        "</soapenv:body>\n" + "</soapenv:Envelope>");
    return stringbuffer.tostring (); }//parsing message, obtaining from the name of the distal pointValue private static string Getxmlmessagebyname (String Xmlresult, String nodename) throws Documentexception {docu
        ment doc = Documenthelper.parsetext (xmlresult);
        Defaultxpath XPath = new Defaultxpath ("//" + nodename);
        Xpath.setnamespaceuris (Collections.singletonmap ("ns1", "http://cn.gov.chinatax.gt3nf.nfzcpt.service/"));
        List List = Xpath.selectnodes (DOC);
            if (!list.isempty () && list.size () > 0) {element node = (element) list.get (0);
        return Node.gettext ();
    Return "";
 }
}

For the following message format, take the node value:

<?xml version= "1.0" encoding= "Utf-8"?> <soap:envelope xmlns:soap= "http://schemas.xmlsoap.org/soap/" envelope/"> <soap:Body> <ns1:doserviceresponse xmlns:ns1=" Http://cn.gov.chinatax.gt3nf.nfzcpt.service /"> <return><! [Cdata[<taxml><service><sid>sid Value </sid><channelType>10</channelType>< Version>1.0</version><transeq>uuid</transeq><tranreqdate>20171204</tranreqdate ></service><bizcontent><bizresult>
Related Article

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.