【发布时间】:2019-04-05 07:22:03
【问题描述】:
我想使用 POST 方法传递 2 个参数,并从使用 php 开发的 API 中获取响应。我想使用 GSON 和 Volley。
我写了一个方法并在onCreate方法中调用它。这是我的方法类-
private void loadDetailed() {
//Toast.makeText(DetailedBoatActivity.this, "Called", Toast.LENGTH_SHORT).show();
Intent i = getIntent();
Integer boat_id = i.getExtras().getInt("boat_id");
Integer owner_id = i.getExtras().getInt("owner_id");
Gson gson = new Gson();
Map<String, Integer> jsonMap = new HashMap<>();
jsonMap.put("boat_id", boat_id);
jsonMap.put("owner_id", owner_id);
JSONObject jsonObject = new JSONObject(jsonMap);
Log.d("jsonObject", String.valueOf(jsonObject));
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DETAILED_BOAT_URL, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(DetailedBoatActivity.this, "Try", Toast.LENGTH_SHORT).show();
JSONArray array = new JSONArray(response);
Log.i("array1", String.valueOf(array));
} catch (JSONException e) {
Toast.makeText(DetailedBoatActivity.this, "Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(jsonObjectRequest);
}
但我的 API 没有任何响应。这是我的代码-
public function boatDetails($id, $owner_id){
$stmt = $this->con->prepare("SELECT * FROM `boat_details` WHERE id=".$id);
$stmt->execute();
$resultSet = $stmt->get_result();
$boat_details = array();
while($result = $resultSet->fetch_assoc()){
$boat_details[] = $result;
}
return $boat_details;
}
我已手动检查。我使用以下代码获取 JSON 格式的值 -
require_once '../includes/dboperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//if($_GET['boat_id']){
$db = new DbOperations();
$resultSet = $db->boatDetails($_POST['boat_id'], $_POST['owner_id']);
echo json_encode($resultSet);
//}
}
请帮助我传递参数并返回对显示实体的响应。
【问题讨论】:
标签: php android json android-volley gson