我正在尝试为我的 android 应用程序构建 Web 服务。但我在将参数发送到 php 时遇到问题。我正在将这些代码块用于 Http-Post。
public String requestJson(String method, JSONObject parameters) {
try {
int TIMEOUT_MILLISEC = 10000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
String tmpUrl = serviceUrl.trim() + (serviceUrl.trim().endsWith("/") ? method : "/" + method);
HttpPost request = new HttpPost(tmpUrl);
request.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8");
if (parameters != null)
{
request.setEntity(new StringEntity(parameters.toString(), HTTP.UTF_8));
}
HttpResponse response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
final String jsonResponse = EntityUtils.toString(response.getEntity());
if (statusCode != HttpStatus.SC_OK) {
Log.w(TAG, "Error in web request: " + statusCode);
Log.w(TAG, jsonResponse);
return null;
} else {
Log.i(TAG, jsonResponse);
return jsonResponse;
}
} catch (Exception e) {
Log.e(TAG, "Error in fetching JSON due to -> " + e.toString());
}
return null;
}
public String testFunction() {
try {
JSONObject param = new JSONObject();
param.put("testID", 123);
JsonCevabi = requestJson("test.php", param);
if (JsonCevabi != null) {
JSONObject jo = new JSONObject(JsonCevabi);
JSONArray ja = new JSONArray(jo.getString("d"));
@SuppressWarnings("unchecked")
List<SampleEntity> resultList = (List<SampleEntity>) new Gson().fromJson(ja.toString(), new TypeToken<List<SampleEntity>>() {
}.getType());
return JsonCevabi;
}
else
return null;
} catch (Exception e) {
return null;
}
}
我的php代码是这样的;
<?php
$id = json_decode($_POST['testID']);
$json = "{d:[{sample1:'".$id."',sample2:'value12'}]}";
$response = $_GET["callback"] . $json;
echo $response;
?>
我想要做的是将 TestID 参数发送到 php。我正在努力让我回到这个值。
但我得到 {d:[{sample1:'',sample2:'value12'}]}
我想要的是 {d:[{sample1:'123',sample2:'value12'}]}
我错过了什么?
编辑:我发现了类似的问题,但没有帮助; Android JSON HttpClient 使用 HttpResponse 将数据发送到 PHP 服务器