簡單實用java調用WSDL接口,並解析返回數據格式

最近因爲一些數據問題,需要跟第三方對接數據,OK!要聯繫方式,聯繫上了,然後人家就給我一個文檔,說所有東西上面都有.....,沒辦法只能自己慢慢琢磨了!

然後發現他們是WSDL的方式調用的,百度了一下,WSDL是基於 XML 的用於描述 Web Services 以及如何訪問 Web Services 的語言,以前只是知道有這麼各東西,但是從來沒用過,只能研究一下怎麼搞了!以下只是我個人研究得一點點淺見哈,只是爲了以後複習使用,有什麼問題請各位指出哈!

一般拿到WSDL的接口文檔以後,先得看下接口地址能不能調通,就是直接把接口地址放在瀏覽器裏面看下能不能放文檔xml文檔內容。能訪問到以後,就是要學會怎麼看xml裏面的內容了。

 

這個文檔內容看起來很多,剛開始看的時候一頭霧水,然後就是百度百度再百度,這裏就直接說怎麼用吧,感覺這裏面有用的就最上面的xmlns對應的那一串地址以及<wsdl:types>裏面的東西了,可以看到<wsdl:types>的<xs:element>裏面有個name,這個就是對應的可以這個接口下面可以調用的方法了,sequence裏面就是需要傳入的參數。下面是java具體調用的代碼

package com.zyh.car.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.annotation.Resource;


public class GetEquipMsgUtils {

   

    public static void main(String[] args) throws IOException {
        //第一步:創建服務地址,也就是提供的WSDL的接口地址
        URL url = new URL("http://xxxxxxxxxxxxxxxx/xxxx/xxxxxxxxx?wsdl");
        //第二步:打開一個通向服務地址的連接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //第三步:設置參數
        //3.1發送方式設置:POST必須大寫
        connection.setRequestMethod("POST");
        //3.2設置數據格式:content-type
        connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        //3.3設置輸入輸出,因爲默認新創建的connection沒有讀寫權限,
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //第四步:組織SOAP數據,發送請求,
        String soapXML = getXML(方法名,參數1,參數2);
        //將信息以流的方式發送出去
        OutputStream os = connection.getOutputStream();
        os.write(soapXML.getBytes());
        //第五步:接收服務端響應,打印
        int responseCode = connection.getResponseCode();
        if(200 == responseCode){//表示服務端響應成功
        //獲取當前連接請求返回的數據流
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            StringBuilder sb = new StringBuilder();
            String temp = null;
            while(null != (temp = br.readLine())){
                sb.append(temp);
            }

            /**
             * 打印結果
             */
            System.out.println("---"+sb.toString());
            try{
                //對返回的數據進行JSON格式化
                System.out.println(xml2Json(sb.toString()));
            }catch (Exception e){
                e.printStackTrace();
            }
            is.close();
            isr.close();
            br.close();
        }
        os.close();
    }

    
//請求入參
public static String getXML(String method,int begin,int end){
    String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tns=\"http://guizhou.fire.and.rescue\">"
                        +"<soapenv:Header></soapenv:Header> "
                         +"<soapenv:Body>  "
                            +"<tns:"+method+"> "//方法名
                                +"<tns:offset>"+begin+"</tns:offset>"//參數1
                                +"<tns:row_count>"+end+"</tns:row_count>"//參數2
                            +"</tns:"+method+">"
                        +"</soapenv:Body>"
                    +"</soapenv:Envelope>";
    return soapXML;
}


    /**
     * xml轉json
     *
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml轉json
     *
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }
}

然後運行,就能接收到接口的返回數據了!如果有中文亂碼的話,就把編輯器以及項目的編碼格式都改成UTF-8的就可以了

--------------------------------------------------------------------------------------------

補充說明:當獲取當前連接請求返回的數據流並讀取的時候,如果返回數據不完整就會拋異常

java.io.IOException: Premature EOF

這個問題問度娘,都說讀取的時候

String temp = null;
while(null != (temp = br.readLine())){
  sb.append(temp);
}

這一段改成

int BUFFER_SIZE = 1024;
char[] buffer = new char[BUFFER_SIZE]; // or some other size,
int charsRead = 0;
while ( (charsRead  = br.read(buffer, 0, BUFFER_SIZE)) != -1) {
    sb.append(buffer, 0, charsRead);
}

這樣子就好了,但是我試過了還是會拋異常,找了好久都沒找到具體的解決辦法,如果有大神看見帖子,望指導一下應該怎麼做纔行..................,這個問題我也會持續跟蹤,有解決辦法了再第一時間發出來

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章