我正在使用 Slim 框架通过 GET
方法在 Android 中执行 REST API。我对检索表的所有值没有任何问题,例如 cars
。
当我尝试通过 id
访问 Car
的 name
时,问题就来了。我在 Slim 框架上创建了方法,它运行良好:
获取方法
$app->get("/cars/:idCar",function($idCar) use($app)
{
try{
$connection = getConnection();
$dbh = $connection->prepare("SELECT name FROM cars WHERE idCar = ?");
$dbh->bindParam(1,$idCar);
$dbh->execute();
$car = $dbh->fetchObject();
$connection = null;
header("HTTP/1.1 200");
header("Content-Type:application/json; charset=utf-8");
echo json_encode($car,JSON_UNESCAPED_UNICODE );
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
});
如果我把 url 放在我的浏览器上:
http://IP of my computer/project/cars/1
它返回给我:
{"name":"Car1"}
所以在GET
方法中没有任何问题。
问题出在我尝试执行 HttpGet
时,因为我无法执行必须执行的操作。我现在拥有的:
AsyncTask 中的 HttpGet 方法
class FindCar extends AsyncTask<Integer, Integer, Void> {
protected void onPreExecute(){
}
protected Void doInBackground(Integer... idCar) {
String url = "http://IP of my computer/project/cars/" + idCar[0].intValue();
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
try {
HttpResponse resp = httpClient.execute(method);
String respStr = EntityUtils.toString(resp.getEntity());
JSONArray respJSON = new JSONArray(respStr);
for (int i = 0; i < respJSON.length(); i++) {
JSONObject obj = respJSON.getJSONObject(i);
String name = obj.getString("name");
}
} catch (Exception ex) {
}
return null;
}
protected void onProgressUpdate(){
}
protected void onPostExecute(){
}
}
它给了我一些问题:
- 我应该只为一个属性创建一个
JSONArray
吗? - 在我的 AsyncTask 中获取名称的最佳做法是什么?
- 通过传递给
AsyncTask
的Car
的id
获取name
后,如何才能我从AsyncTask
? 中返回它
- 我应该创建一个
NameValuePair
来设置我的id
的值吗?
提前致谢!
最佳答案
您不需要 JSONArray(因为响应中没有方括号)!请尝试代替
JSONArray respJSON = new JSONArray(respStr);
for (int i = 0; i < respJSON.length(); i++) {
JSONObject obj = respJSON.getJSONObject(i);
String name = obj.getString("name");
}
以下内容:
JSONObject respJSON = new JSONObject(respStr);
String name = respJSON.getString("name");
至于返回结果——将它从 doInBackground 返回到 onPostExecute 方法,然后将它存储在某个地方(你可以在屏幕上显示它,因为 onPostExecute 在 UI 线程上运行)。要从 doInBackground 返回值,请更改 AsyncTask<Integer, Integer, Void>
的最后一个类型参数来自 Void
到其他类型。
最佳做法是不要使用 AsyncTask 并且不要手动解析 JSON(如果可能的话):) Retrofit 将是一个不错的选择
关于Android - 带参数的 HttpGet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32108803/