首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android HTTP POST 正確傳參:使用 HttpClient + NameValuePair 避免服務端收到 null

     編輯:程式設計綜合問答

錯誤代碼分析

原代碼將參數拼在 URL 後(?UID=xxx&URL=yyy),但同時用 HttpURLConnection 做 POST 卻未寫入請求體,服務端按 POST 取參數自然為 null。

標準 POST 寫法

List params = new ArrayList<>();
params.add(new BasicNameValuePair("UID", androidId));
params.add(new BasicNameValuePair("URL", resultFinal));
params.add(new BasicNameValuePair("device", "android"));

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://yourserver.com/api/endpoint"); // 僅基礎 URL
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");

關鍵點

  • **URL 不帶參數**,參數通過 setEntity 放入請求體(application/x-www-form-urlencoded)。
  • 使用 UrlEncodedFormEntity 自動編碼特殊字符。
  • 服務端按 $_POST['UID'] (PHP) 或 request.getParameter("UID") (Java) 取值。

Android 6.0+ 棄用 HttpClient

建議遷移至 **OkHttp** 或 **Retrofit**:

// OkHttp 同步 POST
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
    .add("UID", androidId)
    .add("URL", resultFinal)
    .add("device", "android")
    .build();
Request request = new Request.Builder()
    .url("https://yourserver.com/api/endpoint")
    .post(formBody)
    .build();
try (Response response = client.newCall(request).execute()) {
    String result = response.body().string();
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved