简体   繁体   中英

How to send POST request in JSON and response in JSON using volley (Android)

    private void login(){
   // Post params to be sent to the server
   Map<String, String> params = new HashMap<String, String>();
   params.put("user_id", username);
   params.put("password", password);


   JsonObjectRequest req = new JsonObjectRequest(login_URL, new JSONObject(params),
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   VolleyLog.v("Response:%n %s", response.toString());
               }
           }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
           VolleyLog.e("Error: ", error.getMessage());
       }
   }){
       /**
        * Passing some request headers
        * */
       @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           HashMap<String, String> headers = new HashMap<String, String>();
           headers.put("Content-Type", "application/json; charset=utf-8");
           return headers;
       }

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

I got below error: E/Volley: [1] 10.onErrorResponse: Error:

i dont know where the problem

json send as post: { "":"", "":"", "":"", } json response as: {"":""}

You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. Also scrap out the new 'JSONObject(params)'.

Now override the getParams() method just above your getParams override and add the content of your login method there. You should return params.

It should work. Let me know if you have any challenges. :).

A very good example would be here

Volley library can be integrated using grader and if you want to know about implementation of Requests in volley then following link can give you all types of requests you can make with volley and how to implement it .

Here you go

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM