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

Android 以 XML 格式與伺服器交換資料的實作

編輯:關於 Android 程式設計

除了 JSON,XML 也是常見的資料交換格式,特別是在對接較舊的企業系統時。以 XML 溝通的關鍵有兩點:送出時要正確宣告 Content-Type,接收時要依編碼正確還原字串。

一、發送 XML 資料

public static void main(String[] args) throws Exception {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
               + "<videos><video><title>中國</title></video></videos>";
    String path = "https://localhost:8083/videoweb/video/manage.do?method=getXML";

    byte[] entity = xml.getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);

    // 指定內容類型為 XML,並標明編碼
    conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
    conn.setRequestProperty("Content-Length", String.valueOf(entity.length));

    OutputStream outStream = conn.getOutputStream();
    outStream.write(entity);

    if (conn.getResponseCode() == 200) {
        System.out.println("發送成功");
    } else {
        System.out.println("發送失敗");
    }
}

二、接收 XML 資料(伺服器端)

public ActionForward getXML(ActionMapping mapping, ActionForm form,
                            HttpServletRequest request, HttpServletResponse response)
                            throws Exception {
    InputStream inStream = request.getInputStream();
    byte[] data = StreamTool.read(inStream);
    String xml = new String(data, "UTF-8");
    System.out.println(xml);
    return mapping.findForward("result");
}

幾個實作上的關鍵

編碼必須全程一致。XML 宣告中的 encoding="UTF-8"、getBytes("UTF-8")、new String(data, "UTF-8") 三處必須完全相同。任何一處寫成預設編碼,中文就會變成亂碼——這是 XML 資料交換最常見的問題。

先用 byte 陣列算長度。Content-Length 要的是位元組數而非字元數。範例先轉成 byte[] 再取 length,順序是對的。若直接對含中文的字串取 length(),數值會偏小,導致伺服器端接收到截斷的內容。

別忘了釋放串流。範例中 OutputStream 沒有關閉,實務上應改用 try-with-resources 確保關閉,否則連線會殘留。

伺服器端的寫法有年代性。範例中的 ActionMapping、ActionForm、ActionForward 都屬於已停止維護的 Struts 1 框架。若你在維護舊專案,這段程式碼可直接參考;若是新專案,Spring MVC 中用 @RequestBody 搭配 JAXB 就能輕鬆完成 XML 綁定。

最後補充一點趨勢判斷:XML 的語法冗長、解析成本較高,在目前的新專案中已大量被 JSON 取代。若還是選擇 XML,通常的理由是要對接既有系統、需要 XML Schema 驗證,或涉及 SOAP WebService 協定。若沒有這些限制,JSON 搭配 Gson 或 Jackson 會是更省力的選擇。

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