利用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得到。

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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值