編輯:關於 Android 程式設計
前一篇(AndroidAnnotations 使用之 @Rest 獲取資源及用戶登入驗證)處理的是登入時 JSESSION 欄位的問題,本篇把重點放在回應資料的 JSON 轉換上。
@Rest 的官方參考文件:https://github.com/excilys/androidannotations/wiki/Rest-API#rest
直接瀏覽器請求 https://192.168.0.101:8080/cbvr/getUserInfoList.action 時,回傳的內容其實就是 JSON。上一篇把它當成 String 收下來,再用 GSON 手動解析,這樣做可行,但顯得多此一舉——既然框架本身支援轉換器,換一個 converter 不就得了?
package com.example.testaa;
import org.androidannotations.annotations.rest.Accept;
import org.androidannotations.annotations.rest.Post;
import org.androidannotations.annotations.rest.Rest;
import org.androidannotations.api.rest.MediaType;
import org.androidannotations.api.rest.RestClientErrorHandling;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
@Rest(rootUrl = "https://192.168.0.101:8080/cbvr",
converters = {GsonHttpMessageConverter.class})
public interface UserService extends RestClientErrorHandling {
@Post("/getUserInfoList.action")
@Accept(MediaType.APPLICATION_JSON)
ResponseEntity<DataGrid> getUserInfoList();
}
寫好之後記得把 GSON 相關的 Jar 匯入專案。然而一執行卻收到這樣的錯誤:
05-02 16:58:32.644: W/System.err(7454): org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.example.testaa.DataGrid] and content type [text/html;charset=UTF-8]
一開始我以為是 Android 端的事,換了好幾個轉換器,錯誤依舊。仔細讀訊息才發現線索藏在最後一段:content type 是 text/html。回頭檢查後端,每次輸出 JSON 時都寫了:
response.setContentType("text/html;charset=UTF-8");
把它改成正確的媒體類型:
response.setContentType("application/json;charset=utf-8");
再執行一次就通過了。這也提醒我們:Content-Type 是 client 選擇 converter 的唯一依據,後端標錯,前端再怎麼努力也無效。
Userinfo,對應 JSON 陣列中的每一筆紀錄:
package com.example.testaa;
public class Userinfo {
/**
* {field:'yhm',title:'用戶名',width:150},
* {field:'pwd',title:'密碼',width:150},
* {field:'yhqx',title:'用戶權限',width:150},
* {field:'zcsj',title:'注冊時間',width:150},
* {field:'bz',title:'備注',width:180}
*/
private String id;
private String yhm;
private String pwd;
private String yhqx;
private String zcsj;
private String bz;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getYhm() { return yhm; }
public void setYhm(String yhm) { this.yhm = yhm; }
public String getPwd() { return pwd; }
public void setPwd(String pwd) { this.pwd = pwd; }
public String getYhqx() { return yhqx; }
public void setYhqx(String yhqx) { this.yhqx = yhqx; }
public String getZcsj() { return zcsj; }
public void setZcsj(String zcsj) { this.zcsj = zcsj; }
public String getBz() { return bz; }
public void setBz(String bz) { this.bz = bz; }
}
DataGrid,對應外層的 total 與 rows 結構:
package com.example.testaa;
public class DataGrid {
private int total;
private Userinfo[] rows;
public Userinfo[] getRows() { return rows; }
public void setRows(Userinfo[] rows) { this.rows = rows; }
public int getTotal() { return total; }
public DataGrid(int total, Userinfo[] rows) {
this.total = total;
this.rows = rows;
}
public DataGrid() { }
public void setTotal(int total) { this.total = total; }
}
package com.example.testaa;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.api.rest.RestErrorHandler;
import org.springframework.web.client.RestClientException;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
@EBean
public class MyErrorHandler implements RestErrorHandler {
@RootContext Context context;
@Override
public void onRestClientExceptionThrown(RestClientException e) {
// TODO Auto-generated method stub
e.printStackTrace();
Log.d("REST", e.toString());
showError();
}
@UiThread
void showError() {
Toast.makeText(context, "Rest Error...", Toast.LENGTH_SHORT).show();
}
}
package com.example.testaa;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.springframework.http.ResponseEntity;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
private static final String TAG = "AAREST";
@ViewById Button getUser;
@ViewById TextView myTextView;
@RestService UserService userService;
@Bean MyErrorHandler errorHandlerForUserService;
@AfterViews
void afterView() {
// 設置 ErrorHandler
userService.setRestErrorHandler(errorHandlerForUserService);
}
/** 獲取用戶列表 */
@Click
void getUser() {
getUserInBackground();
}
/** 獲取用戶列表,無需登入 */
@Background
void getUserInBackground() {
// String result = userService.getUserInfoList();
// Gson gson = new Gson();
// DataGrid dataGrid = gson.fromJson(result, DataGrid.class);
ResponseEntity<DataGrid> responseEntiy = userService.getUserInfoList();
if (null == responseEntiy) {
return;
}
DataGrid dataGrid = responseEntiy.getBody();
Userinfo[] userinfos = dataGrid.getRows();
String string = "";
for (Userinfo userinfo : userinfos) {
string = string + "user:" + userinfo.getYhm();
Log.d(TAG, userinfo.getYhm());
}
Log.d(TAG, string);
displayTextView(string);
}
@UiThread
void displayTextView(String string) {
myTextView.setText(string);
}
}
整個專案以 AndroidAnnotations 框架搭建,本次重點是打通後端與 Android 之間的 JSON 互動:後端輸出正確的 Content-Type,前端掛上 GsonHttpMessageConverter,回應就能直接變成 Java 物件,省下手動解析的那一段。
需要注意的副作用是:把 Response 的 setContentType 改掉,可能影響原網站對瀏覽器的呈現,因此實務上宜依場景評估,或改用能同時滿足兩邊的設定方式。
專案下載:https://download.csdn.net/detail/nuptboyzhb/7283863
Android 開發筆記(一百):三種折疊式列表實作與動畫處理
刷朋友圈動態時常看到這種設計:內容長的只顯示前幾行,想讀完整再點擊展開。這樣整頁列表的高度比較平均,不會被個別長文佔掉半個螢幕。文章列表也是同樣思路。本文整理三種實作方式
Android NDK 入門:從 JNI 到 so 庫
建立專案與宣告 JNI 先建立 Android 專案,新增 HelloJni 類別,用 loadLibrary 載入 native 函式庫,再用 native 宣告要由
5555 端口被佔用導致模擬器無法識別的解決方法
「昨天模擬器還好好的,今天 Eclipse 突然就識別不了了。」——這個問題困擾過不少 Android 開發者。排查之後發現,罪魁禍首往往是某個手機助手類軟件:它們為了實
Android 手勢衝突完全解析:事件分發機制與兩種解法
Android 的手勢衝突問題,根源在事件分發機制。整套流程由三個方法共同決定: public boolean dispatchTouchEvent(MotionEv