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

Posted

技术标签:

【中文标题】android volley post json ID 并从 PHP 服务器返回结果【英文标题】:android volley post json ID and get result back from PHP server 【发布时间】:2016-07-30 01:43:59 【问题描述】:

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

javacode

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));

【问题讨论】:

您的错误到底是什么?它会返回一些东西吗? 【参考方案1】:

我会这样修改请求:

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));

希望对你有帮助!!!

【讨论】:

请注意,这不起作用,json 仍然会被发送。实际上 getParams 永远不会被调用 thnx 伙计们,我最终做的是,有一个正常的字符串请求,但后来将其转换为字符串数组,然后读取数组【参考方案2】:

问题是您发送 json 但您希望 php 中有参数。

有两种解决方案:

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);

【讨论】:

【参考方案3】:

我使用了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);

【讨论】:

以上是关于android volley post json ID 并从 PHP 服务器返回结果的主要内容,如果未能解决你的问题,请参考以下文章

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

android与服务器交互总结(json,post,xUtils,Volley)

带有标头和原始 json 正文的 Volley POST 请求

使用 Volley 发送带有 JSON 数据的 POST 请求

您如何使用 Android Volley API?

在 json 对象参数 Volley post 中发送令牌头