編輯:關於 Android 程式設計
拜接口時,請求參數要序列化成 JSON,返回結果又要反序列化回對象。手拼字符串顯然不靠譜,Gson 這類庫才是正解。下面用一個完整的例子走一遍:請求參數是 JSON,返回結果也是 JSON。
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
new Thread() {
public void run() {
GetJsonDataByPost httpJsonPost = new GetJsonDataByPost();
String[] pathArray = httpJsonPost.getPathArray("dev0003");
for (int i = 0; i < pathArray.length; i++) {
System.out.println(pathArray[i]);
}
}
}.start();
}
}
網絡請求放在子線程裡,這是 Android 的硬性要求——主線程做網絡操作會直接拋 NetworkOnMainThreadException。
public class GetJsonDataByPost {
static private String Service_URL = "Your url";
static private int TIMEOUT = 120 * 1000;
String mMethodName;
public String[] getPathArray(String devnum) {
try {
mMethodName = "GetPicByUser";
// 1. 把調用 API 的參數封裝成 JSON
String jsonParams = JsonUtils.getJsonRequestParams(devnum);
// 2. 發請求,拿回 JSON 格式的結果
String jsonResult = getJsonDataByPost(jsonParams);
// 3. 從結果中取出 pic 數組
return JsonUtils.getJsonRequestResponse(jsonResult);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getJsonDataByPost(String json) {
String result = null;
try {
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
entity.setContentType("application/json");
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, TIMEOUT);
client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, TIMEOUT);
if (mMethodName == null) {
return null;
}
HttpPost httpPost = new HttpPost(Service_URL + mMethodName);
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
StringBuffer buffer = new StringBuffer();
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader bufferReader = new BufferedReader(inputReader);
String str = new String("");
while ((str = bufferReader.readLine()) != null) {
buffer.append(str);
}
bufferReader.close();
result = buffer.toString();
System.out.println("---> API 的請求結果 result=" + result);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
這裡的關鍵是 setContentType("application/json") 加上 StringEntity,讓服務端知道請求體是 JSON 而不是表單。
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class JsonUtils {
// 封裝請求 API 的參數,請求時轉為 JSON
static class JsonRequestParams {
String devsn;
int uploadid;
float healthScore;
}
// 封裝 API 返回的結果,響應時由 JSON 轉為該對象
static class JsonRequestResult {
String resultcode;
int uploadid;
String[] pics;
float beat;
String crtime;
}
// 對象 → JSON
public static String getJsonRequestParams(String devnum) {
try {
JsonRequestParams params = new JsonRequestParams();
params.devsn = devnum;
params.uploadid = 0;
params.healthScore = 0.0f;
Gson gson = new Gson();
String json = gson.toJson(params);
System.out.println("---> 封裝後的請求參數 " + json);
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// JSON → 對象
public static String[] getJsonRequestResponse(String ret) {
try {
Gson gson = new Gson();
JsonRequestResult result = gson.fromJson(ret, JsonRequestResult.class);
if (result.resultcode.contains("ok")) {
System.out.println("---> resultcode=" + result.resultcode);
System.out.println("---> beat=" + result.beat);
System.out.println("---> uploadid=" + result.uploadid);
System.out.println("---> crtime=" + result.crtime);
return result.pics;
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return null;
}
}
Gson 的省心之處就在這裡:字段名與 JSON 的 key 同名,它會自動完成映射,連 String[] 這種數組結構都能直接對應,完全不用手写解析。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Everyone"
android:layout_centerInParent="true" />
</RelativeLayout>
一是字段命名。Gson 默認按字段名精確匹配,如果服務端用下劃線風格(result_code),可以在字段上加 @SerializedName("result_code"),或者構造 Gson 時指定 FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES。
二是解析失敗的處理。示例裡只捕獲了 JsonSyntaxException,實際項目中服務端返回 HTML 錯誤頁、空響應、字段類型不匹配都很常見,最好把異常捕得寬一些,並對關鍵字段做空值判斷,別讓一個髒數據把整個流程帶崩。
Android Handler 的使用(一):從異步訊息談起
基本概念 Handler 主要用於異步訊息的處理:發出訊息後,訊息先進入一個佇列,發送函數立刻返回;另一個部分則逐一從佇列中取出訊息並處理。也就是說,發送與接收並非同步進
Android 搜索功能實戰——SearchView 與搜索框完整實現
引言 在應用程式中,我們經常需要提供搜索服務,比如搜索聯絡人、搜索商品資訊等。我們可以自己在佈局中自訂搜索框並實現搜索邏輯,但還有一種更省事的做法:使用 Android
從頭梳理 Android 大圖片加載的 OOM 問題:降採樣與 LruCache 雙管齊下
寫 Android 應用的時候幾乎繞不開圖片。問題在於,圖片的實際尺寸往往遠大於我們真正需要的顯示尺寸——相機拍出來的照片分辨率可能是屏幕的十幾倍。而每個應用程序的可用內
打造高質感下拉刷新動畫:Android 自訂 RefreshView 實作
近來看到不少精緻又有質感的動畫效果,若能把這些動畫融入自己的專案,App 的整體觀感勢必加分不少。今天要帶大家拆解一個來自 Yalantis 的精美下拉刷新動畫。 先欣賞