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

Android 向伺服器發送 JSON 資料的實作教學

編輯:關於 Android 程式設計

本文講解如何從 Android 端把 JSON 資料送到伺服器,內容偏向基礎入門。核心步驟包括:使用 Gson 將物件序列化為 JSON、透過 HttpClient 送出、再由伺服器解析並回傳結果。

一、Android 端發送 JSON

public void sendJsonToServer() {
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost httpPost = new HttpPost(constant.url);
        HttpParams httpParams = new BasicHttpParams();
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        Gson gson = new Gson();
        String str = gson.toJson(initData());
        nameValuePair.add(new BasicNameValuePair("jsonString", URLEncoder.encode(str, "utf-8")));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        httpPost.setParams(httpParams);
        Toast.makeText(Main.this, "發送的資料:\n" + str.toString(), Toast.LENGTH_SHORT).show();
        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine != null && statusLine.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Toast.makeText(Main.this, "伺服器處理返回結果:" + readInputStream(entity.getContent()),
                    Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(Main.this, "沒有返回相關資料", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(Main.this, "發送失敗,可能伺服器忙碌,請稍後再試", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private static String readInputStream(InputStream is) throws IOException {
    if (is == null) return null;
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    int len = 0;
    byte[] buf = new byte[1024];
    while ((len = is.read(buf)) != -1) {
        bout.write(buf, 0, len);
    }
    is.close();
    return URLDecoder.decode(new String(bout.toByteArray()), "utf-8");
}

/* 填充資料源 */
public List<Product> initData() {
    List<Product> persons = new ArrayList<Product>();
    for (int i = 0; i < 5; i++) {
        Product p = new Product();
        p.setLocation("所在位置");
        p.setName("名稱" + i);
        persons.add(p);
    }
    return persons;
}

其中 Gson 負責把 Product 集合轉換成 JSON 字串,送出前再以 URLEncoder 編碼,避免特殊字元造成問題。

二、伺服器端接收並回傳

這裡以 ASP.NET 建立一個 androidtest.aspx 頁面為例:

protected void Page_Load(object sender, EventArgs e) {
    if (Request["jsonString"] != null) {
        string json = Request["jsonString"].ToString().Trim();
        json = HttpUtility.UrlDecode(json);
        try {
            string str = json.Substring(0, json.Length - 1);// 去掉最後一個 ]
            str = str.Substring(1);// 去掉第一個 [
            string[] sArray = Regex.Split(str, "},");
            JavaScriptSerializer jss = new JavaScriptSerializer();
            for (int i = 0; i < sArray.Length; i++) {
                if (i < sArray.Length - 1) {
                    sArray[i] += "}";
                }
                ProductBillList list = jss.Deserialize<ProductBillList>(sArray[i]);
                Response.Write(list.location + list.name + "\n");
            }
        } catch {
            Response.Write("出現異常");
        }
    } else {
        Response.Write("接收資料失敗");
    }
}

public class ProductBill {
    public List<ProductBillList> ProductBillLists { get; set; }
}

public class ProductBillList {
    public String name { get; set; }
    public String location { get; set; }
}

伺服器接收到 jsonString 後先解碼,再用 JavaScriptSerializer 反序列化為物件,最後輸出處理結果。

整體流程就是:物件 → Gson 序列化 → URL 編碼 → POST 送出 → 伺服器解析 → 回傳結果。若對 Gson 不熟悉,建議先了解它如何把集合轉成 JSON,會更清楚整個環節。

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