WebService 调用,最简单的入门

本例是一个测试QQ是否在线的webService,所以要求你必须能上互联网,否则可能无法使用。

步骤一:新建一个java工程,工程名随便你自己定义

步骤二:新建一个类,类文件名为:QQOnlineService .java

内容如下:

import java.io.*;
import java.net.*;

public class QQOnlineService {
 public static void main(String[] args) throws Exception {
  String urlString = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";
  String xmlFile = "D:\\QQOnlineService.XML";  //文件内容参照一下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();
 }
}

步骤三:新建一个XML文件,文件名为:QQOnlineService.XML,位置存放在D盘下面(因为上面我写的路径就是这个,呵呵,你自己也可以更改的)

内容如下:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <qqCheckOnline xmlns="http://WebXml.com.cn/">
      <qqCode>860933306</qqCode><!--你要查询的QQ号码-->
    </qqCheckOnline>
  </soap:Body>
</soap:Envelope>

步骤四:运行QQOnlineService .java 文件,你在控制台将会看到它返回的结果。

返回内容如下(result.xml 文件)

<?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 mlns="http://WebXml.com.cn/">
<qqCheckOnlineResult>N</qqCheckOnlineResult><!--N 代表QQ不在线  Y代表QQ在线-->
</qqCheckOnlineResponse>
</soap:Body>
</soap:Envelope>

Ok ?应该没什么问题吧,有问题给我留言!祝你好运!

原文地址:https://www.cnblogs.com/yimu/p/yimu.html