伺服器端期望 $.post(url, {param: jsonString}),Android 端嘗試將所有欄位包成一個 JSON 物件作為 param 值發送,導致伺服器解析失敗。
jQuery $.post 的第二個參數為 鍵值對物件,會自動編碼為 application/x-www-form-urlencoded 格式,每個屬性變成獨立表單欄位。非單一 param 欄位包含 JSON 字串。
List params = new ArrayList<>();
params.add(new BasicNameValuePair("action", "get"));
params.add(new BasicNameValuePair("result", "user"));
params.add(new BasicNameValuePair("category", "base"));
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", password_md5));
HttpPost post = new HttpPost(URL);
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
| 錯誤方式 | 正確方式 |
|---|---|
單一欄位 param={"action":"get",...} | 多欄位 action=get&result=user&... |
| 伺服器需解析 JSON 再解析巢狀參數 | 伺服器直接取得平坦表單參數 |
JSONObject json = new JSONObject();
json.put("action", "get");
json.put("username", user);
// ...
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
但需確認伺服器端實際期望格式,多數 PHP/Java 後端預期表單編碼。