*设为首页
*加入收藏
热门关键字: JAVA
>>当前位置:Java大本营>Web Service>文章内容
如何用Java访问WEB Service
作者: 发布时间:2007-12-03 13:14:50

最近在学习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得到。

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

<?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>



·深入浅出taglib (12-12)
·深入浅出taglib (12-12)
·struts:自定义taglib的开发(12-12)
·java创建TXT文件并进行读、写、修改操(12-12)
·java.library.path(12-12)
·java字符串处理函数集合(12-12)
·Web Service(12-12)
· Integrating Seam with Maven, Netbea(09-12)
· SWT已经是日薄西山了(09-12)
· native2ascii用法(09-12)
· Java 判断是否Cookie禁用 并实现禁用(09-12)
· cfx发布到weblogic(09-12)
复制地址发给您的好友: [推荐文章] [返回顶部] [关闭窗口]
版权所有 Java大本营 1999-2007 转载请注明出处