WebService多種方式調用包含base64Binary的接口

WebService有多種方式調用,在開發一個接口客戶端的時候第一步肯定是先用soapUI調用接口瞭解情況。平時工作中最爲簡單的方法是生成客戶端,有java的wsimport或Axis2的wsdl2java來生成。另外還有一種HttpURLConnection的方式,不需求其它的包就能調用。其實webService本質也是Http請求,只不過請求體是 soap協議的方式。
base64Binary類型一般用於上傳附件時用到,也就是將 文件的二進制流轉成base64的方式傳遞給服務端


soapUI

網上太多資料不
轉自:Web Service單元測試工具實例介紹之SoapUI

使用Axis2生成客戶端

1.生成服務端代碼命令
WSDL2Java -uri wsdl文件全路徑 -p 包名 -d xmlbeans -s -ss -sd -ssi -o 生成的java代碼存放路徑

2.生成客戶端包代碼命令
WSDL2Java -uri wsdl文件全路徑 -p 包名 -d xmlbeans -s -o 生成的java代碼存放路徑

WSDL2Java命令參數說明:
-uri  指定*.wsdl文件,可以帶具體路徑;
-p  指定生成代碼的包名
-d <databinding>   : 指定databingding,例如,adb,xmlbean,jibx,jaxme and jaxbri 默認adb
-o  指定生成代碼放置的路徑;
-ss 表示要生成服務端代碼;
-ssi 表示要生成代碼中,先生成接口類,再生成實現類;

axis2-1.5.6下載地址
從網上下載axis後,解壓到 D:\Apache 目錄下面,再在CMD中執行如下命令:
axis2 會默認生成 adb 方式

cd D:\Apache\axis2-1.5.6
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_80
set AXIS2_HOME=D:\Apache\axis2-1.5.6
WSDL2Java -uri D:\Apache\axis2-1.5.6\CapitalSysWS.xml -p com.client.capital -o capital

在 D:\Apache\axis2-1.5.6 目錄下面會多出一個 capital 文件夾,裏面就是生成的客戶端的java文件
在eclipse裏新建一個項目,將axis2-1.5.6/lib裏的jar包引入到工程中。再將生成的客戶端代碼添加進去。
這裏寫圖片描述
調用客戶端

package org.web.service.capitalSys;

import java.rmi.RemoteException;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.rpc.ServiceException;

import org.web.service.capitalSys.CapitalSysWSStub.GenerateBillServiceResponse;

/**
 * <b>function:</b>上傳文件WebService客戶端
 * http://localhost/easws/services/CapitalSysWS?wsdl
 */
public class CapiitalSysClient {

    public static void main(String[] args) throws RemoteException, ServiceException {
        // 使用Fiddler 能監聽到
        System.setProperty("http.proxyHost", "localhost");
        System.setProperty("http.proxyPort", "8888");

        String target = "http://localhost/easws/services/CapitalSysWS?wsdl";
        CapitalSysWSStub stub = new CapitalSysWSStub(target);
        CapitalSysWSStub.GenerateBillService service = new CapitalSysWSStub.GenerateBillService();
        service.setXmlReq(xmlReq3()); // 流動資金申請信息
        service.setAccessory(generateDataHandler()); // 上傳本地文件

        GenerateBillServiceResponse res = stub.generateBillService(service);
        String str = res.get_return();
        System.out.println("============返回結果============");
        System.out.println(str);

        System.out.println(str);
    }

    private static DataHandler generateDataHandler() {
        String fileName = "readMe.txt";
        String filePath = System.getProperty("user.dir") + "\\WebContent\\" + fileName;
        DataHandler dataHandler = new DataHandler(new FileDataSource(filePath));
        return dataHandler;
    }

    public static String xmlReq3(){
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xml.append("<data>");
        xml.append("...");   // 略
        xml.append("</data>");
        return xml.toString();
    }

}

使用HttpURLConnection調用

注意這裏的soap 的xml 都不一樣,最好是用上面的客戶端調用一次,再用Fiddler抓一下包。看包裏面是怎麼傳的,再來寫這個。
這裏寫圖片描述

package org.web.service.capitalSys;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.rpc.ServiceException;

import sun.misc.BASE64Encoder;

/**
 * <b>function:</b>上傳文件WebService客戶端
 * http://localhost/easws/services/CapitalSysWS?wsdl
 */
public class CapiitalSysClient2 {

    public static void main(String[] args) throws ServiceException, IOException {
        String target = "http://localhost/easws/services/CapitalSysWS?wsdl";

        StringBuffer sb = new StringBuffer(getBody(xmlReq3(), getByteArrayByFile()));

        URL u = new URL(target);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setDefaultUseCaches(false);
        conn.setRequestProperty("Content-Type",
                "application/soap+xml; charset=UTF-8; action=\"urn:generateBillService\"");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("POST");

        OutputStream output = conn.getOutputStream();
        if (null != sb) {
            byte[] b = sb.toString().getBytes("UTF-8");
            output.write(b, 0, b.length);
        }
        output.flush();
        output.close();

        sb = new StringBuffer();
        InputStream input = conn.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        int c = -1;
        while (-1 != (c = bufferedReader.read())) {
            sb.append((char) c);
        }
        bufferedReader.close();
        String result = sb.toString().replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", "\"");

        System.out.println(result);
    }

    public static String getBody(String data, String binary) {
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml version='1.0' encoding='UTF-8'?>");
        xml.append("<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">");
        xml.append("<soapenv:Body><ns1:generateBillService xmlns:ns1=\"http://services.beews.zte.com\">");
        xml.append("<ns1:xmlReq><![CDATA[");
        xml.append("%s");
        xml.append("]]></ns1:xmlReq>");
        xml.append("<ns1:accessory>");
        xml.append("%s");
        xml.append("</ns1:accessory>");
        xml.append("</ns1:generateBillService></soapenv:Body></soapenv:Envelope>");
        return String.format(xml.toString(), data, binary);
    }

    // public static void main(String[] args) throws IOException {
    // System.out.println(CapiitalSysClient2.getByteArrayByFile());
    // }

    private static String getByteArrayByFile() throws IOException {
        sun.misc.BASE64Encoder base64Encoder = new BASE64Encoder();
        String fileName = "readMe.txt";
        String filePath = System.getProperty("user.dir") + "\\WebContent\\" + fileName;

        File file = new File(filePath);
        InputStream input = new FileInputStream(file);
        byte[] byt = new byte[input.available()];
        input.read(byt);
        return base64Encoder.encode(byt);
    }

    // 對外其他報賬單
    public static String xmlReq3() {
        StringBuffer xml = new StringBuffer();
        xml.append("<data>");
        xml.append("..."); // 略
        xml.append("</data>");
        return xml.toString();
    }

}

wsdl文件

CapitalSysWS.xml:

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://services.beews.zte.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://services.beews.zte.com">
    <wsdl:documentation>CapitalSysWS</wsdl:documentation>
    <wsdl:types>
        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://services.beews.zte.com">
            <xs:element name="generateBillService">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="xmlReq" nillable="true" type="xs:string"/>
                        <xs:element minOccurs="0" name="accessory" nillable="true" type="xs:base64Binary"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
            <xs:element name="generateBillServiceResponse">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="return" nillable="true" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="generateBillServiceRequest">
        <wsdl:part name="parameters" element="ns:generateBillService"/>
    </wsdl:message>
    <wsdl:message name="generateBillServiceResponse">
        <wsdl:part name="parameters" element="ns:generateBillServiceResponse"/>
    </wsdl:message>
    <wsdl:portType name="CapitalSysWSPortType">
        <wsdl:operation name="generateBillService">
            <wsdl:input message="ns:generateBillServiceRequest" wsaw:Action="urn:generateBillService"/>
            <wsdl:output message="ns:generateBillServiceResponse" wsaw:Action="urn:generateBillServiceResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="CapitalSysWSSoap11Binding" type="ns:CapitalSysWSPortType">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
        <wsdl:operation name="generateBillService">
            <soap:operation soapAction="urn:generateBillService" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:binding name="CapitalSysWSSoap12Binding" type="ns:CapitalSysWSPortType">
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
        <wsdl:operation name="generateBillService">
            <soap12:operation soapAction="urn:generateBillService" style="document"/>
            <wsdl:input>
                <soap12:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:binding name="CapitalSysWSHttpBinding" type="ns:CapitalSysWSPortType">
        <http:binding verb="POST"/>
        <wsdl:operation name="generateBillService">
            <http:operation location="CapitalSysWS/generateBillService"/>
            <wsdl:input>
                <mime:content type="text/xml" part="generateBillService"/>
            </wsdl:input>
            <wsdl:output>
                <mime:content type="text/xml" part="generateBillService"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="CapitalSysWS">
        <wsdl:port name="CapitalSysWSHttpSoap11Endpoint" binding="ns:CapitalSysWSSoap11Binding">
            <soap:address location="http://localhost:80/easws/services/CapitalSysWS.CapitalSysWSHttpSoap11Endpoint/"/>
        </wsdl:port>
        <wsdl:port name="CapitalSysWSHttpSoap12Endpoint" binding="ns:CapitalSysWSSoap12Binding">
            <soap12:address location="http://localhost:80/easws/services/CapitalSysWS.CapitalSysWSHttpSoap12Endpoint/"/>
        </wsdl:port>
        <wsdl:port name="CapitalSysWSHttpEndpoint" binding="ns:CapitalSysWSHttpBinding">
            <http:address location="http://localhost:80/easws/services/CapitalSysWS.CapitalSysWSHttpEndpoint/"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章