兩種介面傳送資料協議(xml和json)

y_keven發表於2014-07-10

   規範性介面開發中,一般資料是以json或者xml的格式傳送的,而不是字串的形式直接返回給介面呼叫者;下面介紹這兩種格式的編寫方法。

   下面兩種資料傳送方式是介面輸出端的編寫。需引入的包如下:

<span style="font-family:KaiTi_GB2312;font-size:18px;">importjava.io.PrintWriter;

importjava.io.StringWriter;

importjavax.servlet.http.HttpServletResponse;

importorg.dom4j.Document;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.XMLWriter;</span>


1.傳送 XML 協議的格式資料

<span style="font-family:KaiTi_GB2312;font-size:18px;">   /**

    * xml 格式資料

    *

    * @param response

    * @param doc

    */

    publicstaticvoidoutDocToXML(HttpServletResponse response, Document doc) {

       // 以下程式碼請注意編碼順序

       response.setCharacterEncoding("utf-8");

       response.setContentType("text/xml;charset=utf-8");

       response.setHeader("Pragma", "no-cache");

       response.setHeader("Cache-Control", "no-cache");

       response.setDateHeader("Expires", 0);

       PrintWriter out = null;

       StringWriter writer = new StringWriter();

       OutputFormat format = OutputFormat.createPrettyPrint(); //

       format.setEncoding("UTF-8");

       XMLWriter xmlwriter = new XMLWriter(writer,format);

 

       try {

            out = response.getWriter();

           xmlwriter.write(doc);

       } catch (Exception e) {

           e.printStackTrace();

       }

       out.print(writer.toString());

       out.close();

}</span>


 

2.傳送 json 協議的格式資料

<span style="font-family:KaiTi_GB2312;font-size:18px;">/**

    * json 資料格式

    *

    * @param response

    * @param data

    * @param type

    */

    protectedvoidsendData(HttpServletResponse response, Object data) {

       if (data != null) {

           response.setCharacterEncoding("utf-8");

           response.setContentType("application/json;charset=UTF-8");

           response.setHeader("Pragma", "no-cache");

           response.setHeader("Cache-Control", "no-cache");

           response.setDateHeader("Expires", 0);

           PrintWriter out = null;

           try {

                out = response.getWriter();

                out.print(data);

                out.close();

           } catch (Exception e) {

                e.printStackTrace();

           }

       }

    }</span>

轉正請指明出處:blog.csdn.net/yangkai_hudong

相關文章