使用Java用戶端類調用c# WebService和xml rpc server)

來源:互聯網
上載者:User
   本文介紹一個非常實用的用戶端工具類來調用C# WebServices和 rpc server,這個類的源碼是從網上下載的,我在部落格網做項目的時候一直使用這個類來調試C# WebServices和MetaWeblog API。順便在這裡也給大家介紹一下C#如何處理此類發送的xml資料。
  • 使用這個類不用安裝任何第三方工具,因為採用http的方式發送xml檔案,所以你只需要安裝好JDK就可以了。執行此類還可以獲得WebServices或xml rpc server返回的xml字元流,你可以根據返回的xml資料來進行其他程式處理。通過這種方式實現了Java平台和平台的資料交換和WebService調用。
    下面是此類的原始碼SOAPClient4XG.java:

    /**
    * SOAPClient4XG. Read the SOAP envelope file passed as the second
    * parameter, pass it to the SOAP endpoint passed as the first parameter, and
    * print out the SOAP envelope passed as a response. with help from Michael
    * Brennan 03/09/01
    *
    *
    * @author Bob DuCharme
    * @version 1.1
    * @param SOAPUrl URL of SOAP Endpoint to send request.
    * @param xmlFile2Send A file with an XML document of the request.
    *
    * 5/23/01 revision: SOAPAction added
    */

    import java.io.*;
    import java.net.*;

    public class SOAPClient4XG {
    public static void main(String[] args) throws Exception {

    if (args.length < 2) { //小於
    System.err.println("Usage: java SOAPClient4XG " +
    "http://soapURL soapEnvelopefile.xml" +
    " [SOAPAction]");
    System.err.println("SOAPAction is optional.");
    System.exit(1);
    }

    String SOAPUrl = args[0];
    String xmlFile2Send = args[1];

    String SOAPAction = "";
    if (args.length > 2) //大於
    SOAPAction = args[2];

    // Create the connection where we're going to send the file.
    URL url = new URL(SOAPUrl);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;

    // Open the input file. After we copy it to a byte array, we can see
    // how big it is so that we can set the HTTP Cotent-Length
    // property. (See complete e-mail below for more on this.)

    FileInputStream fin = new FileInputStream(xmlFile2Send);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    // Copy the SOAP file to the open connection.
    copy(fin,bout);
    fin.close();

    byte[] b = bout.toByteArray();

    // Set the appropriate HTTP parameters.
    httpConn.setRequestProperty( "Content-Length",
    String.valueOf( b.length ) );
    httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
    httpConn.setRequestProperty("SOAPAction",SOAPAction);
    httpConn.setRequestMethod( "POST" );
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);

    // Everything's set up; send the XML that was read in to b.
    OutputStream out = httpConn.getOutputStream();
    out.write( b );
    out.close();

    // Read the response and write it to standard out.

    InputStreamReader isr =
    new InputStreamReader(httpConn.getInputStream());
    BufferedReader in = new BufferedReader(isr);

    String inputLine;

    while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

    in.close();
    }

    // copy method from From E.R. Harold's book "Java I/O"
    public static void copy(InputStream in, OutputStream out)
    throws IOException {

    // do not allow other threads to read from the
    // input or write to the output while copying is
    // taking place

    synchronized (in) {
    synchronized (out) {

    byte[] buffer = new byte[256];
    while (true) {
    int bytesRead = in.read(buffer);
    if (bytesRead == -1) break;
    out.write(buffer, 0, bytesRead);
    }
    }
    }
    }
    }

    編譯:javac SOAPClient4XG.java
    啟動並執行命令格式: java -classpath . SOAPClient4XG http://localhost/BokeServices/Service1.asmx c:loginReq.xml http://tempuri.org/UserLoginReq,不過先不要運行上面的命令,先介紹一下命令列的意思,http://localhost/BokeServices/Service1.asmx是C# WebService的地址,c:loginReq..xml裡的內容是調用的WebService方法的xml檔案, http://tempuri.org是WebService方法的命名空間,一定要有,否則調用失敗,如果你在C# WebServices中使用了方法預設的命名空間的話,就使用http://tempuri.org,否則要與C#中定義的一致,UserLoginReq是C# WebServices的方法名。注意xml檔案中的方法名和參數名是與C# WebServices的方法名、參數名是一一對應的(參數順序是可以顛倒的)。
    我先介紹一個簡單的例子(c:loginReq.xml),這個xml檔案調用了遠程C# WebService的UserLoginReq方法,並帶UserAcc(使用者名稱)和UserPwd(口令)兩個參數,調用成功後C#會自動返回一個xml格式的SOAP包。
    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
    <UserLoginReq xmlns="http://tempuri.org/">
    <UserAcc>baozheng</UserAcc>
    <UserPwd>mypwd</UserPwd>

    </UserLoginReq>
    </soap:Body>
    </soap:Envelope>

    現在看一下C# WebServices的UserLoginReq的方法的定義:
    public struct UserLoginResp
    {
    public string UserAcc;
    public int Result;
    }

    [WebMethod]

    public UserLoginResp UserLoginReq(string UserAcc,string UserPwd,int ReqFrom)
    {

    }

    注意結構UserLoginResp,C# WebServices返回SOAP資訊時會自動將UserLoginResp結構轉換成xml的格式。

    用此類做xml rpc server 的用戶端也很簡單,下文是一個用戶端rpc.xml檔案,調用了xml rpc server 端實現的metaWeblog.deletePost方法。
    <?xml version="1.0" encoding="utf-8"?>
    <methodCall>
    <methodName>metaWeblog.deletePost</methodName>
    <params>
    <param><value>appKeyValue</value></param>
    <param><value>746</value></param>

    <param><value>baozheng</value></param>
    <param><value>Hello123</value></param>
    </params>
    </methodCall>

    調用命令的格式:
    java -classpath %CLASSPATH%;. SOAPClient4XG. http://192.168.25.97:8080/BokeeXmlRpc/xml-rpc rpc.xml

    對比調用WebServices的命令列,可以看出調用xml rpc server的命令列少一個方法名參數。http://192.168.25.97:8080/BokeeXmlRpc/xml-rpc 是提供xml rpc 調用的server端servlet地址,關於如何用apache xml rpc技術實現MetalogAPI的文章將在近期整理髮布。

    註:上文的左右角括弧為保證正常發貼替換為全形。

    作者:王保政
    QQ:19803446
    Msn:baozhengw999@hotmail.com
    Email:baozhengw@netease.com

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.