Java使用SOAP获取webservice实例解析

来源:互联网 发布:上古世纪男性捏脸数据 编辑:程序博客网 时间:2024/06/05 18:52

这篇文章是根据一位cnblogs上的一位大大,做了些修改而已

他的文章:走喽~~

进入正文,为了怕资源丢失,我选择了全部黏贴复制了一遍!

1、webservice提供方:http://www.webxml.com.cn/zh_cn/index.aspx
2、下面我们以“获得腾讯QQ在线状态”为例。
参数截图如下图:

以下是 SOAP 1.1 请求和响应示例。所显示的占位符需替换为实际值。

[http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?op=qqCheckOnline] 点击前面的网址,查看对应参数信息。

3、Java代码

package com.jyxp.soap;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;public class SoapQQTest {public static void main(String[] args) {// TODO Auto-generated method stubtry {(new SoapQQTest()).sendSms();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}private void sendSms() throws Exception {String qqCode = "55555";String urlString = "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx";String xml = SoapQQTest.class.getClassLoader().getResource("SendInstantSms.xml").getFile();String xmlFile = replace(xml, "qqCodeTmp", qqCode).getPath();        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();        byte[] datas = readInputStream(httpConn.getInputStream());        String result=new String(datas);        //打印返回结果        System.out.println("result:" + result);}/**     * 文件内容替换     *      * @param inFileName 源文件     * @param from     * @param to     * @return 返回替换后文件     * @throws IOException     * @throws UnsupportedEncodingException     */    public static File replace(String inFileName, String from, String to)            throws IOException, UnsupportedEncodingException {        File inFile = new File(inFileName);        BufferedReader in = new BufferedReader(new InputStreamReader(                new FileInputStream(inFile), "utf-8"));        File outFile = new File(inFile + ".tmp");        PrintWriter out = new PrintWriter(new BufferedWriter(                new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));        String reading;        while ((reading = in.readLine()) != null) {            out.println(reading.replaceAll(from, to));        }        out.close();        in.close();        //infile.delete(); //删除源文件        //outfile.renameTo(infile); //对临时文件重命名        return outFile;    }        /**     * 从输入流中读取数据     * @param inStream     * @return     * @throws Exception     */    public static byte[] readInputStream(InputStream inStream) throws Exception{        ByteArrayOutputStream outStream = new ByteArrayOutputStream();        byte[] buffer = new byte[1024];        int len = 0;        while( (len = inStream.read(buffer)) !=-1 ){            outStream.write(buffer, 0, len);        }        byte[] data = outStream.toByteArray();//网页的二进制数据        outStream.close();        inStream.close();        return data;    }}
4、SendInstantSms.xml文件如下,放在src目录下

<?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>qqCodeTmp</qqCode>    </qqCheckOnline>  </soap:Body></soap:Envelope>

5、然后自己测试,得到的数据如下

result:<?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>
如上,黄色背景的N,我们根据QQ返回的数据【返回数据:String,Y = 在线;N = 离线;E = QQ号码错误;A = 商业用户验证失败;V = 免费用户超过数量】就表示不在线,呵呵……

以上是从那位大大的博客转的,

下面是自己的完善。

1、先向大家推荐个好工具,应该不少人都知道了,就是Fiddler,这是一款数据追踪工具,

配置:Tools >Fiddler Options > Connections >把Fiddler listens on port:改为下面你要设置的端口(下面我设置的8888) >并且把Allow remote computers to connect 勾选上。

2、如果数据反馈不回来的话,我们可以用它设置下代理,找到返回的数据,

(1、)把上面Java代码中的

HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
改为如下

Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress("127.0.0.1", 8888));                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy);
就可以抓取到返回的详细数据。[注:在没有打开Fiddler的情况下,就把代理去掉,换成之前的!!否则会报错的]

3、如果传递多个参数值的话,我们再用上面的replace()方法,最终得到的结果是值替换了最后一个,下面共享下,一次替换多个字符的代码。有人可能直接在SendInstantSms.xml文件中把值改成参数,这样是可以的,但是不利于安全呢,所以我们用临时文件,然后再删除掉。

public static File replace(String inFileName, String[] from, String[] to)            throws IOException, UnsupportedEncodingException {        File inFile = new File(inFileName);        BufferedReader in = new BufferedReader(new InputStreamReader(                new FileInputStream(inFile), "utf-8"));        File outFile = new File(inFile + ".tmp");        PrintWriter out = new PrintWriter(new BufferedWriter(                new OutputStreamWriter(new FileOutputStream(outFile), "utf-8")));        String reading;        StringBuffer sb = new StringBuffer();        while ((reading = in.readLine()) != null) {            sb.append(reading + "\n");        }        String newString = sb.toString();        for (int i = 0; i < from.length; i++) {newString = newString.replaceAll(from[i], to[i]);}        out.println(newString);                out.close();        in.close();        return outFile;    }

4、还有声明下,在参考的博客中,他说分析的是Soap1.2的,那是错误的,如下才是Soap1.2的格式,相信大家一眼就看出区别了!

请看链接也OK ->再穿越一次、嗖~~

POST /webservices/qqOnlineWebService.asmx HTTP/1.1Host: www.webxml.com.cnContent-Type: application/soap+xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  <soap12:Body>    <qqCheckOnline xmlns="http://WebXml.com.cn/">      <qqCode>string</qqCode>    </qqCheckOnline>  </soap12:Body></soap12:Envelope>