2016-04-08 61 views
2

我很努力地做这个工作,基本上我从前面的活动中使用intent得到一个id,现在我想把这个id发送到服务器,所以它返回所有关联的数据与此ID。android volley post json ID并从PHP服务器获取结果

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

到底什么是你的错误吗?它会返回什么吗? –

回答

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仍将发送。其实getParams将永远不会被调用 – djodjo

+1

thnx球员,我最终做的是,有一个正常的字符串请求,但稍后将其转换为字符串数组,然后读取数组 –

0

问题是你发送json,但你期望params在你的php。

有2个解决方案:

1)更新PHP接受JSON不只是post数据

2)更新凌空请求发送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); 
2

我用的http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put这个例子和coverted字符串响应字符串数组,工作对我来说

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