編輯:關於 Android 程式設計
本文講解如何從 Android 端把 JSON 資料送到伺服器,內容偏向基礎入門。核心步驟包括:使用 Gson 將物件序列化為 JSON、透過 HttpClient 送出、再由伺服器解析並回傳結果。
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,會更清楚整個環節。
RecyclerView 添加 Header 與 Footer,並適配水平布局的左右結構
折騰了整整一個下午,踩過不少坑:最麻煩的是當 LayoutManager 設為水平方向時,頭尾佈局必須改成「左右結構」,否則寬高約束完全錯位;另外還遇到某個 item 需
可滑動的 Tab 頁:RadioGroup + ViewPager + Fragment 實作
用 RadioGroup 搭配 ViewPager 與 Fragment 實作可滑動的 Tab 頁,結構簡單卻相當靈活——RadioGroup 負責互斥選中狀態,View
打造順手好用的 Android 模擬器:完整設定指南
預設的模擬器有多難用 預設狀態下的 Android 模擬器,最顯眼的問題是界面醜:視窗佔掉整個螢幕的龐大空間,還莫名其妙地擺著一個實體螢幕鍵盤。 但如果你真的用過,還有
Android 雙緩衝技術實作手寫畫板
本文分享一個以雙緩衝技術實作的手寫畫板,供同好參考。一、什麼是雙緩衝概念其實很單純:當程式需要往某個 View 上繪圖時,並不直接畫上去,而是先畫進記憶體中的一張 Bit