java 如何调用webservice

本文介绍了一种使用Java直接发送SOAP请求来查询QQ在线状态的方法。该方法通过向指定的WebService地址发送包含XML文档的POST请求,并获取返回的XML响应,实现了简单的QQ在线状态查询功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习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";//此为提供的webservice地址
        String xmlFile = "QQOnlineService.XML";//发给对方的xml文档,在webservice说明中,查看soap发送部分即可
        String soapActionString = "http://WebXml.com.cn/qqCheckOnline";//此为调用的方法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;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值