java 如何調用webservice

最近在學習Web Service,發現了一個國內的Web Service提供站點,其中最簡單的是查詢QQ在線狀態服務。我通過Java直接發送SOAP請求文件訪問Web Service成功,這種方式實現比較簡單,不需要第三方的軟件包。

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

class QQOnlineService {
    public static void main(String[] args) throws Exception {
        String urlString = "";//此爲提供的webservice地址
        String xmlFile = "QQOnlineService.XML";//發給對方的xml文檔,在webservice說明中,查看soap發送部分即可
        String soapActionString = "";//此爲調用的方法qqCheckOnline和命名空間

        URL url = new URL(urlString);

        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();;

        File fileToSend=new File(xmlFile);
        byte[] buf=new byte[(int)fileToSend.length()];
        new FileInputStream(xmlFile).read(buf);
        httpConn.setRequestProperty( "Content-Length",String.valueOf( buf.length ) );
        httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
        httpConn.setRequestProperty("soapActionString",soapActionString);
        httpConn.setRequestMethod( "POST" );
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write( buf );
        out.close();
       
        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(),"utf-8");
        BufferedReader in = new BufferedReader(isr);
       
        String inputLine;
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("result.xml")));//本地生成的xml文檔
        while ((inputLine = in.readLine()) != null){
            System.out.println(inputLine);
            bw.write(inputLine);
            bw.newLine();
        }
        bw.close();
        in.close();
    }
}
程序用到的 QQOnlineService.XML文件可以通過預先訪問http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx得到。

查詢結果文件如下,對其進一步編程可以實現更爲靈活的查詢功能。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <qqCheckOnlineResponse xmlns="http://WebXml.com.cn/">
            <qqCheckOnlineResult>N
            </qqCheckOnlineResult>
        </qqCheckOnlineResponse>
    </soap:Body>
</soap:Envelope>

 

 

說明:

如果調用的方法需要xml文檔的參數,則需要把xml文檔參數中的<>轉換爲&lt;&gt;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章