Send POST request with JSON data using Volley

前端 未结 8 624
梦谈多话
梦谈多话 2020-11-22 12:07

I would like to send a new JsonObjectRequest request:

  • I want to receive JSON data (response from server): OK
  • I want to send JSON form

8条回答
  •  悲哀的现实
    2020-11-22 12:53

    • Create an object of RequestQueue class.

      RequestQueue queue = Volley.newRequestQueue(this);
      
    • Create a StringRequest with response and error listener.

       StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener() {
          @Override
          public void onResponse(String response) {
              mPostCommentResponse.requestCompleted();
          }
      }, new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
              mPostCommentResponse.requestEndedWithError(error);
          }
      }){
          @Override
          protected Map getParams(){
              Map params = new HashMap();
              params.put("user",userAccount.getUsername());
              params.put("pass",userAccount.getPassword());
              params.put("comment", Uri.encode(comment));
              params.put("comment_post_ID",String.valueOf(postId));
              params.put("blogId",String.valueOf(blogId));
      
              return params;
          }
      
          @Override
          public Map getHeaders() throws AuthFailureError {
              Map params = new HashMap();
              params.put("Content-Type","application/x-www-form-urlencoded");
              return params;
          }
      };
      
    • Add your request into the RequestQueue.

      queue.add(jsObjRequest);
      
    • Create PostCommentResponseListener interface just so you can see it. It’s a simple delegate for the async request.

      public interface PostCommentResponseListener {
      public void requestStarted();
      public void requestCompleted();
      public void requestEndedWithError(VolleyError error);
      }
      
    • Include INTERNET permission inside AndroidManifest.xml file.

      
      

提交回复
热议问题