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

簡易實作 Android 客戶端與 Servlet 服務端的資料交互

編輯:關於 Android 程式設計

本文示範如何讓 Android 客戶端透過 GET 方式發送資料到服務端,由服務端查詢資料庫後,再以 JSON 格式返回資料給客戶端解析。

一、GET 傳參格式

GET 方式的參數附加在 URL 之後,格式如下:

https://127.0.0.1/AndroidService/android/upload?title=aaa&timelength=90

其中 ? 之後的 title=aaa&timelength=90 就是參數,多個參數之間以 & 連接。

二、客戶端連接伺服器並取得資料

客戶端透過 HttpURLConnection 發送請求,取得伺服器返回的資料(主要為 JSON 字串):

/**
 * 取得伺服器的資料
 * @param url
 * @return
 */
public static String connect(URL url) {
    InputStream inputStream = null;
    HttpURLConnection connection = null;
    StringBuffer sb = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3000);
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        if (connection.getResponseCode() == 200) {
            inputStream = connection.getInputStream();
            // 進行字元編碼轉換
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            sb = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
    return new String(sb);
}

三、服務端 Servlet 實作

服務端主要是一個 Servlet,透過 doGet() 與 doPost() 處理提交參數並返回資料。把該 Web 專案部署到 Tomcat 即可:

public class MyTest extends HttpServlet {
    private JSONArray infos;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 別呼叫 super.doGet(),否則永遠不會返回資料給客戶端
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        infos = new JSONArray();
        PrintWriter out = resp.getWriter();
        try {
            // 重要!編碼格式處理,避免中文亂碼
            String s = new String(req.getParameter("name").getBytes("iso-8859-1"), "UTF-8");
            infos = DbUtils.getData(s);
            // 把資料寫入回應
            out.write(infos.toString());
            out.flush();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }
}

四、JSON 資料解析

客戶端拿到 JSON 字串後,先取出 JSON 物件,再用鍵值對的形式逐一取出其中的資料即可。

五、web.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
    https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name></display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>MyTest</servlet-name>
        <servlet-class>MyTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyTest</servlet-name>
        <url-pattern>/MyTest</url-pattern>
    </servlet-mapping>
</web-app>

要特別注意的是:如果用 360 共享 WIFI 進行測試,使用的是無線網卡的 IP,而不是乙太網路(有線)的 IP,這點在連線除錯時經常被忽略。

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