当前位置: 代码迷 >> Web前端 >> 怎么用Java访问WEB Service
  详细解决方案

怎么用Java访问WEB Service

热度:95   发布时间:2012-11-17 11:14:15.0
如何用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>

TAG: Service web service

?

http://www.cn-java.com/www1/?action-viewnews-itemid-4789

  相关解决方案