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

Android HTTP 通訊實作:送出排行榜資料、解析 JSON 並下載頭像圖片

編輯:關於 Android 程式設計

最近在做的遊戲專案需要一個排行榜。畫面是一個列表,每列顯示排名、玩家名稱、頭像與分數,共 100 筆;列表下方另外用一個元件顯示玩家自己的排名。

需求是這樣的:每次進入排行榜畫面,就把玩家名稱與分數送到伺服器;伺服器排序後取出前 100 名,再加上玩家自己那一筆,總共 101 筆;因為客戶端還要顯示頭像,回傳的資料裡也必須附上头像圖片的下載路徑。伺服器最後把結果打包成一份 JSON 回傳。

伺服器回傳的 JSON 大致長這樣

{
  "rank": [
    {"person":"曹操","index":1,"score":35852},
    {"person":"曹操","index":2,"score":32563},
    {"person":"孫權","index":3,"score":10000},
    {"person":"劉備","index":4,"score":9638}
  ],
  "base":"(伺服器位址)",
  "head": [
    {"person":"曹操","filename":"/caocao/20130718185726036.png","size":12343},
    {"person":"孫權","filename":"/sunqun/20130718185726046.png","size":12343},
    {"person":"劉備","filename":"/liubei/20130718185726056.png","size":12343}
  ]
}

其中 rank 的每個物件包含人物名稱、排名與分數;head 的每個物件包含人物名稱、圖片檔名與檔案大小;base 則是伺服器的位址前綴。

整體流程

1. 進入排行榜畫面,把玩家資料 POST 到伺服器。
2. 取得回傳的 JSON,解析出 rank 陣列、head 陣列與 base 字串。
3. 依圖片路徑把頭像下載到本機。
4. 建立 ResultMessage 類別,屬性為排名、人物名稱、本機頭像路徑、分數。
5. 解析 rank 時逐筆建立 ResultMessage,加進 List 後回傳。

整個實作可以拆成三個類別:LoadImage、ResultMessage、Upload。

為什麼下載圖片前要多檢查一次?

每次進入排行榜都會重新向伺服器要一次圖片路徑,因此必須先判斷本機是否已有這張圖。但只檢查「檔案存在」並不夠:如果上次下載途中網路突然斷掉,會留下一個不完整的檔案,下次就會誤判為已完成而永遠不再重下。

解法是把伺服器提供的檔案大小一起拿來比對,只有「檔案存在」且「大小一致」時才跳過下載。

LoadImage.java

package com.joye3g.http;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpStatus;

public class LoadImage {

    private static final int SUCCES = 1;  // 下載成功
    private static final int ERRO = -1;   // 下載失敗
    private static final int EXIST = 0;   // 檔案已存在

    private static int result = EXIST;
    private String localPath;

    public LoadImage(String localPath) {
        this.localPath = localPath;
    }

    public int download(String urlPathPrefix, String filename, long size) throws IOException {
        String filePath = localPath + File.separator
                + filename.substring(filename.lastIndexOf("/") + 1);

        // 已存在且大小相同就不重下
        if (isFileExist(filePath) && isSizeSame(filePath, size)) {
            return result = EXIST;
        }
        InputStream is = getHttpInputStream(urlPathPrefix + filename);
        File file = createFile(filePath);
        if (is != null) {
            downLoadImage(file, is);
        }
        return result;
    }

    private void downLoadImage(File file, InputStream is) {
        FileOutputStream fs = null;
        try {
            fs = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                fs.write(buffer, 0, len);
            }
            fs.flush();
            result = SUCCES;
        } catch (Exception e) {
            result = ERRO;
            e.printStackTrace();
        } finally {
            try {
                if (fs != null) fs.close();
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private InputStream getHttpInputStream(String urlPath) throws IOException {
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == HttpStatus.SC_OK) {
            return conn.getInputStream();
        }
        return null;
    }

    private boolean isFileExist(String fileName) {
        return new File(fileName).exists();
    }

    private File createFile(String fileName) throws IOException {
        File file = new File(fileName);
        if (!file.createNewFile()) {
            file.delete();
            file.createNewFile();
        }
        return file;
    }

    private boolean isSizeSame(String filePath, long size) {
        return new File(filePath).length() == size;
    }
}

ResultMessage.java

純資料載體,負責把一筆排名包成物件。

package com.joye3g.http;

public class ResultMessage {
    private int index;
    private String name;
    private int score;
    private String imagePath;

    public ResultMessage(int index, String name, int score, String imagePath) {
        this.index = index;
        this.name = name;
        this.score = score;
        this.imagePath = imagePath;
    }

    public String getImagePath() { return imagePath; }
    public void setImagePath(String imagePath) { this.imagePath = imagePath; }
    public int getIndex() { return index; }
    public void setIndex(int index) { this.index = index; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getScore() { return score; }
    public void setScore(int score) { this.score = score; }
}

Upload.java

負責送出請求、接收回應、下載圖片,最後把結果包裝成 List 回傳。建構時傳入玩家名稱、分數與 Context(用來取得 App 安裝路徑與裝置識別碼)。使用方式非常直覺:

Upload upload = new Upload("曹操", 23456, getApplicationContext());
List<ResultMessage> messages = upload.post("伺服器位址");
package com.joye3g.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.telephony.TelephonyManager;

public class Upload {

    private static final String GZIP = "gzip";

    private Context context;
    private JSONObject jsonData;

    public Upload(String name, int score, Context context) {
        jsonData = new JSONObject();
        this.context = context;
        try {
            jsonData.put("person", name);
            jsonData.put("uploaduser", getUUID());
            jsonData.put("score", score);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public List<ResultMessage> post(String url) {
        List<ResultMessage> messages = null;
        try {
            messages = sendHttpResponse(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }

    private List<ResultMessage> sendHttpResponse(String url)
            throws IOException, JSONException {
        URL uri = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset=UTF-8");
        conn.setRequestProperty("accept-encoding", "gzip,deflate");

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(jsonData.toString().getBytes());
        outStream.flush();
        outStream.close();

        return getReturnMessage(conn);
    }

    private List<ResultMessage> getReturnMessage(HttpURLConnection conn)
            throws IOException, JSONException {
        List<ResultMessage> messages = null;
        String content_encode = conn.getContentEncoding();
        String content = null;

        if (conn.getResponseCode() == HttpStatus.SC_OK) {
            if (content_encode != null && content_encode.equals(GZIP)) {
                content = unGzip(conn.getInputStream());
            } else {
                content = readAll(conn.getInputStream());
            }

            JSONObject objMain = new JSONObject(content);
            JSONArray ranks = objMain.getJSONArray("rank");
            JSONArray heads = objMain.getJSONArray("head");
            String base = objMain.getString("base");

            LoadImage load = new LoadImage(getLocalPath());
            Map<String, String> map = new HashMap<String, String>();

            // 先下載頭像,並建立「人物 -> 檔名」的對照表
            for (int i = 0; i < heads.length(); i++) {
                JSONObject head = heads.getJSONObject(i);
                String person = head.getString("person");
                String filename = head.getString("filename");
                long size = head.getLong("size");
                map.put(person, filename);
                load.download(base, filename, size);
            }

            // 最後一筆是玩家自己的成績,另外處理
            messages = new ArrayList<ResultMessage>();
            for (int i = 0; i < ranks.length() - 1; i++) {
                messages.add(rank(ranks.getJSONObject(i), map));
            }
            messages.add(rank(ranks.getJSONObject(ranks.length() - 1), map));
        }
        conn.disconnect();
        return messages;
    }

    private ResultMessage rank(JSONObject rank, Map<String, String> map) throws JSONException {
        int num = rank.getInt("index");
        String person = rank.getString("person");
        String filename = map.get(person);
        String imagePath = getLocalPath() + File.separator
                + filename.substring(filename.lastIndexOf("/") + 1);
        int score = rank.getInt("score");
        return new ResultMessage(num, person, score, imagePath);
    }

    private static String unGzip(InputStream is)
            throws IOException, UnsupportedEncodingException {
        GZIPInputStream in = new GZIPInputStream(is);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
        is.close();
        return new String(out.toByteArray(), "utf-8");
    }

    private static String readAll(InputStream is) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        is.close();
        out.close();
        return new String(out.toByteArray(), "utf-8");
    }

    private String getUUID() {
        final TelephonyManager tm =
                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(
                context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUUID = new UUID(androidId.hashCode(),
                ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        return deviceUUID.toString();
    }

    private String getLocalPath() {
        return context.getApplicationContext().getFilesDir().getAbsolutePath();
    }
}

幾點值得注意的實務問題

執行緒。從 Android 3.0 起,主執行緒禁止進行網路連線,以上程式碼必須放在背景執行緒(AsyncTask、Thread 或各種背景排程機制)中執行,再把結果回傳主執行緒更新 UI。

權限。記得在 Manifest 加上 android.permission.INTERNET,寫檔的話還需要 WRITE_EXTERNAL_STORAGE。

裝置識別碼。用 IMEI 與 SIM 序號湊出的 UUID 在部分機型上會取到 null,且這類識別碼屬於敏感資訊、後續版本也逐步限制取得。若要穩定標識裝置,建議自行產生一組隨機 UUID 存進 SharedPreferences 或改用其他非敏感方案。

字元編碼。請求本文以 getBytes() 送出時未指定編碼,跨平台時容易出問題,實務上請明確寫成 getBytes("UTF-8")。

最後,messages 中每個物件的內容就是:排名、人物名稱、本機頭像圖片路徑、分數,可以直接交給 ListView 的 Adapter 使用。

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