Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android WebServices 源碼分析:拆解 ksoap2-android 的呼叫流程

編輯:關於 Android 程式設計

本文為子墨原創,轉載請註明出處!https://blog.csdn.net/zimo2013/article/details/38037989

在〈Android WebServices 介紹〉一文中,我們簡單介紹了 WebServices 的基礎知識,本篇則深入分析 ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar 的實作源碼。

1. 呼叫 WebServices 的流程

public void getRemoteInfo(String phoneSec) {
    String nameSpace = "https://WebXml.com.cn/";
    String methodName = "getMobileCodeInfo";
    String endPoint = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
    String soapAction = "https://WebXml.com.cn/getMobileCodeInfo";

    // 1. 初始化 SoapObject 對象,為該方法設置參數,相當於信體
    SoapObject request = new SoapObject(nameSpace, methodName);
    request.addProperty("mobileCode", phoneSec);
    request.addProperty("userId", "");

    // 2. 實例化 SoapSerializationEnvelope 對象,相當於信皮
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
    envelope.bodyOut = request;
    envelope.dotNet = true; // 兼容 .net 開發的 Net-Services

    // 3. 實例化 HttpTransportSE 對象,還可以指定訪問的請求時間
    HttpTransportSE transport = new HttpTransportSE(endPoint);
    // HttpTransportSE transport = new HttpTransportSE(endPoint, timeout);

    try {
        // 4. 核心方法調用,soapAction 在 VER12 時無效,且為 POST 請求
        transport.call(soapAction, envelope);
        SoapObject response = (SoapObject) envelope.bodyIn;
        final String result = response.getProperty(0).toString(); // Vector
        toast(result);
    } catch (Exception e) {
        e.printStackTrace();
        toast(e.getMessage());
    }
}

2. transport.call 關鍵源碼分析

call 方法是整個呼叫流程的心臟,主要完成以下幾件事:

public List call(String soapAction, SoapEnvelope envelope, List headers, File outputFile)
        throws HttpResponseException, IOException, XmlPullParserException {

    if (soapAction == null) {
        soapAction = "\"\"";
    }

    // 根據 envelope,將其序列化為一個請求字節數組
    byte[] requestData = createRequestData(envelope, "UTF-8");
    requestDump = debug ? new String(requestData) : null;
    responseDump = null;

    // 建立連線(可指定超時時間)
    ServiceConnection connection = getServiceConnection();
    connection.setRequestProperty("User-Agent", USER_AGENT);

    // SOAPAction 不是 VER12 的有效標頭,因此 VER12 時不加入
    if (envelope.version != SoapSerializationEnvelope.VER12) {
        connection.setRequestProperty("SOAPAction", soapAction);
    }
    if (envelope.version == SoapSerializationEnvelope.VER12) {
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_SOAP_XML_CHARSET_UTF_8);
    } else {
        connection.setRequestProperty("Content-Type", CONTENT_TYPE_XML_CHARSET_UTF_8);
    }
    connection.setRequestProperty("Accept-Encoding", "gzip");

    // 加入使用者自訂標頭
    if (headers != null) {
        for (int i = 0; i < headers.size(); i++) {
            HeaderProperty hp = (HeaderProperty) headers.get(i);
            connection.setRequestProperty(hp.getKey(), hp.getValue());
        }
    }

    // POST 請求
    connection.setRequestMethod("POST");

    // 發送數據,耗時較長,將 requestData 發送至 connection 的輸出流
    sendData(requestData, connection, envelope);
    requestData = null;

    InputStream is = null;
    List retHeaders = null;
    byte[] buf = null;
    int contentLength = 8192;
    boolean gZippedContent = false;
    boolean xmlContent = false;

    // 得到響應碼
    int status = connection.getResponseCode();
    try {
        // 解析響應頭
        retHeaders = connection.getResponseProperties();
        for (int i = 0; i < retHeaders.size(); i++) {
            HeaderProperty hp = (HeaderProperty) retHeaders.get(i);
            if (null == hp.getKey()) {
                continue;
            }
            if (hp.getKey().equalsIgnoreCase("content-length")) {
                if (hp.getValue() != null) {
                    try {
                        contentLength = Integer.parseInt(hp.getValue());
                    } catch (NumberFormatException nfe) {
                        contentLength = 8192;
                    }
                }
            }
            if (hp.getKey().equalsIgnoreCase("Content-Type") && hp.getValue().contains("xml")) {
                xmlContent = true;
            }
            if (hp.getKey().equalsIgnoreCase("Content-Encoding") && hp.getValue().equalsIgnoreCase("gzip")) {
                gZippedContent = true;
            }
        }

        // 首先檢查響應碼
        if (status != 200) {
            throw new HttpResponseException("HTTP request failed, HTTP status: " + status, status);
        }
        if (contentLength > 0) {
            if (gZippedContent) {
                is = getUnZippedInputStream(new BufferedInputStream(connection.openInputStream(), contentLength));
            } else {
                is = new BufferedInputStream(connection.openInputStream(), contentLength);
            }
        }
    } catch (IOException e) {
        // ... 錯誤串流處理,避免把 HTTP 錯誤串流當成 SOAP 回應解析
    }

    if (debug) {
        is = readDebug(is, contentLength, outputFile);
    }

    // 根據 is 流,將流數據解析至 envelope.bodyIn 中
    parseResponse(envelope, is, retHeaders);

    // 釋放資源
    is = null;
    buf = null;
    connection.disconnect();
    connection = null;

    return retHeaders;
}

整段流程可濃縮為:先把 envelope 序列化為請求位元組,設定各項 HTTP 標頭後以 POST 送出;接著讀取響應碼與標頭,判斷是否為 gzip 壓縮或 XML 內容;最後透過 parseResponse 把響應串流解析回 envelope.bodyIn,完成整個 request/response 循環。理解這個流程,除錯與效能調校都會更得心應手。

實例下載:https://download.csdn.net/detail/strawberry2013/7663399

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved