利用Java访问WEB Service

最近在学习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 = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";
        String xmlFile = "QQOnlineService.XML";
        String soapActionString = "http://WebXml.com.cn/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")));
        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得到。

查询结果文件如下,对其进一步编程可以实现更为灵活的查询功能。



   
       
            N
           

       

   


你可能感兴趣的:(利用Java访问WEB Service)