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

以 HttpURLConnection 發送 SOAP/XML 訊息給第三方服務

編輯:關於 Android 程式設計

面試中曾出現過一題:如何發送(並接收)XML 並加以解析。當時雖有接觸卻沒特別留意,於是回來深入研究並記錄於此,與大家一同學習。

以下這個 sendSoapMsg 方法示範了如何以 POST 方式,把一段 SOAP(XML 格式)訊息發送給目標服務,並讀取回應結果:

public static StringBuffer sendSoapMsg(String soapMessage,
                                    String targetUrl, String soapAction, Long timeout) throws Exception
  {
    busLogger.enterFuncDebugLog(soapMessage, soapAction, targetUrl, timeout);
    // 保存響應消息
    HttpURLConnection conn = null;
    BufferedReader bf = null;
    StringBuffer sb = new StringBuffer();

    try
    {
        URL url = new URL(targetUrl);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.addRequestProperty("SOAPAction", soapAction);
        conn.addRequestProperty("Content-type", "text/xml; charset=UTF-8");

        // 設定連線超時時間
        conn.setConnectTimeout(timeout.intValue());

        // 將發送請求參數寫入到 http 請求中
        conn.getOutputStream().write(soapMessage.getBytes());
        conn.getOutputStream().flush();
        conn.getOutputStream().close();

        // 從服務器獲取響應結果
        InputStream in = conn.getInputStream();

        // 從服務器讀取結果
        bf = new BufferedReader(new InputStreamReader(in));
        String s = null;
        while ((s = bf.readLine()) != null)
        {
            sb.append(s);
        }
    }
    catch (Exception e)
    {
        busLogger.excepFuncDebugLog(e);
        throw e;
    }
    finally
    {
        if (null != bf)
        {
            try
            {
                bf.close();
            }
            catch (IOException e)
            {
                busLogger.excepFuncDebugLog(e);
            }
        }
        if (conn != null)
        {
            conn.disconnect();
        }
    }

    busLogger.exitFuncDebugLog(sb.toString());
    return sb;
  }

重點解析

這段程式碼的關鍵步驟如下:

  • 以 POST 方法開啟 HttpURLConnection,並設定 setDoOutput(true) 以便寫入請求內容。
  • 透過 addRequestProperty 加上 SOAPAction 與 text/xml 的 Content-type 標頭,這是 SOAP 溝通的標準做法。
  • 用 getOutputStream 把 XML 字串寫入請求主體,字串內容即為 SOAP 訊息本體。
  • 從 getInputStream 讀取服務器回應,逐行拼接成完整的結果字串。
  • 在 finally 區塊中確實關閉串流並中斷連線,避免資源洩漏。

其中傳入的 soapMessage 參數,其內容就是一段 XML 格式的字串。收到回應後,你就能再進一步用 XML 解析器把回傳的內容拆解成可用的資料。

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