简体   繁体   English

如何使用volley(Android)在JSON中发送POST请求并在JSON中发送响应

[英]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: 我得到以下错误:E / Volley:[1] 10.onErrorResponse:错误:

i dont know where the problem 我不知道问题出在哪里

json send as post: { "":"", "":"", "":"", } json response as: {"":""} json发送为帖子:{“”:“”,“”:“”,“”:“,} json响应为:{”“:”“}

You should add the Request.Method.POST as the first parameter of your new JsonObjectRequest method. 您应该将Request.Method.POST添加为新JsonObjectRequest方法的第一个参数。 Also scrap out the new 'JSONObject(params)'. 还要废弃新的“ JSONObject(params)”。

Now override the getParams() method just above your getParams override and add the content of your login method there. 现在覆盖getParams覆盖上方的getParams()方法,并在那里添加登录方法的内容。 You should return params. 你应该返回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 . Volley库可以使用分级器进行集成,如果您想了解排序中的请求的实现,那么以下链接可以为您提供所有类型的请求,您可以使用齐射以及如何实现它。

Here you go 干得好

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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