Android 客戶端發起登入請求時,伺服器拋出 java.lang.IllegalArgumentException,提示參數不合法或不正確。常見原因在於請求參數構建方式錯誤。
// 錯誤示範:將參數直接拼接在 URL 後
String url = "https://api.example.com/login?username=" + user + "&password=" + pwd;
HttpGet request = new HttpGet(url);
此做法存在多重風險:
@、#、空格)未經 URL 編碼導致參數解析錯誤HttpPost post = new HttpPost("https://api.example.com/login");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pwd));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
URLEncoder.encode(value, "UTF-8") 編碼建議採用 OkHttp、Retrofit 等現代網絡框架,自動處理參數編碼、連接池、重試等細節:
// Retrofit 介面定義
@FormUrlEncoded
@POST("login")
Call<LoginResponse> login(@Field("username") String user, @Field("password") String pwd);
Content-Type: application/x-www-form-urlencoded)參數傳遞失敗多源於手動拼接 URL 導致編碼缺失或格式錯誤。採用標準 POST 表單提交、成熟網絡庫並嚴格進行參數編碼,可從根本上消除此類問題。