原代碼將參數拼在 URL 後(?UID=xxx&URL=yyy),但同時用 HttpURLConnection 做 POST 卻未寫入請求體,服務端按 POST 取參數自然為 null。
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");
setEntity 放入請求體(application/x-www-form-urlencoded)。UrlEncodedFormEntity 自動編碼特殊字符。$_POST['UID'] (PHP) 或 request.getParameter("UID") (Java) 取值。建議遷移至 **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();
}