android volley 发布 json ID 并从 PHP 服务器返回结果

问题描述 投票:0回答:3

我正在努力完成这项工作,基本上我使用意图从之前的活动中获取了一个ID,现在我想将此ID发送到服务器,以便它返回与此ID相关的所有数据。

java代码

final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
                    print response in textview;
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

PHP 服务器

if (!empty($_POST)) {

    $query = " SELECT * FROM table WHERE ID = :ID " ;

    $query_params = array(
        ':ID' => $_POST['ID'],);

    try {
        $statement   = $db->prepare($query);
        $result = $statement->execute($query_params);
    }
    catch (PDOException $ex) {


        $response["success"] = 0;
        $response["message"] = "Database query error";
        die(json_encode($response));

    }

    $result = $statement->fetchAll();

    if($result){

            $data =array();

            foreach($result as $rows){
        $json = array();
        $json["Name"] = $rows["Name"];





        array_push ($data,$json);



            }
     echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
java android post android-volley send
3个回答
2
投票

我使用了http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put的示例,并将字符串响应转换为字符串数组,对我有用

url = "http://httpbin.org/post";
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
        new Response.Listener<String>() 
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        }, 
        new Response.ErrorListener() 
        {
             @Override
             public void onErrorResponse(VolleyError error) {
                 // error
                 Log.d("Error.Response", response);
           }
        }
    ) {     
        @Override
        protected Map<String, String> getParams() 
        {  
                Map<String, String>  params = new HashMap<String, String>();  
                params.put("name", "Alif");  
                params.put("domain", "http://itsalif.info");

                return params;  
        }
    };
    queue.add(postRequest);

0
投票

我会像这样修改请求:

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST,URL,null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
                                   VolleyLog.v("Response:%n %s", response.toString(4));
                                   print response in textview;
                                } catch (JSONException e) {
                                   e.printStackTrace();
                                }

                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        })

                @Override 
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("ID", "1");
                    return params;
                }
          };    

          ApplicationController.getInstance().addToRequestQueue(req);

并且还会像这样修改 PHP 代码:

if (isset($_POST['ID'])) {
     $id = $_POST['ID'];
    try {
        $statement = $db->prepare(SELECT * FROM table WHERE ID = ?);
        $statement->bindValue(1, $id);
        $result = $statement->execute();
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database query error";
        die(json_encode($response));
    }
    $records = array();
    $records = $statement->fetchAll(PDO::FETCH_ASSOC);
    $data = array();
    foreach($records as $record){
        $data["Name"] = $record["Name"];
    }
     echo stripcslashes(json_encode($data, JSON_PRETTY_PRINT));
}

希望有帮助!!!


0
投票

问题是你发送了 json 但你期望 php 中有参数。

有2个解决方案:

1)更新 php 以接受 json 而不仅仅是发布参数

2) 更新 volley 请求以发送 post 参数,但需要 JSONObject

例如,您可以使用此请求:

    public class JsonObjReq extends Request<JSONObject> {


    private final Response.Listener<JSONObject> mListener;
    private final Map<String, String> params;

    public JsonObjReq(int method, String url, Map<String, String> params, Response
                      .Listener<JSONObject> mListener,
                      Response.ErrorListener listener) {
        super(method, url, listener);
        this.mListener = mListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return params;
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);
    }
}

并像这样应用到您的代码:

    final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("ID", "1");

JsonObjReq req = new JsonObjReq(Method.POST, URL, params,
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
                    print response in textview;
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
© www.soinside.com 2019 - 2024. All rights reserved.