Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a POST request using volley with string body?

I'm developing an Android app that communicate with a RESTful web service I wrote. Using Volley for GET methods is awesome and easy, but I can't put my finger on the POST methods.

I want to send a POST request with a String in the body of the request, and retrieve the raw response of the web service (like 200 ok, 500 server error).

All I could find is the StringRequest which doesn't allow to send with data (body), and also it bounds me to receive a parsed String response. I also came across JsonObjectRequest which accepts data (body) but retrieve a parsed JSONObject response.

I decided to write my own implementation, but I cannot find a way to receive the raw response from the web service. How can I do it?

like image 506
itaied Avatar asked Nov 06 '15 19:11

itaied


People also ask

How do I make a volley request?

Use newRequestQueue RequestQueue queue = Volley. newRequestQueue(this); String url = "https://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request. Method.

How do I request post on Android?

build(); Request request = new Request. Builder() . url("https://yourdomain.org/callback.php") // The URL to send the data to .


2 Answers

You can refer to the following code (of course you can customize to get more details of the network response):

try {     RequestQueue requestQueue = Volley.newRequestQueue(this);     String URL = "http://...";     JSONObject jsonBody = new JSONObject();     jsonBody.put("Title", "Android Volley Demo");     jsonBody.put("Author", "BNK");     final String requestBody = jsonBody.toString();      StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {         @Override         public void onResponse(String response) {             Log.i("VOLLEY", response);         }     }, new Response.ErrorListener() {         @Override         public void onErrorResponse(VolleyError error) {             Log.e("VOLLEY", error.toString());         }     }) {         @Override         public String getBodyContentType() {             return "application/json; charset=utf-8";         }          @Override         public byte[] getBody() throws AuthFailureError {             try {                 return requestBody == null ? null : requestBody.getBytes("utf-8");             } catch (UnsupportedEncodingException uee) {                 VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");                 return null;             }         }          @Override         protected Response<String> parseNetworkResponse(NetworkResponse response) {             String responseString = "";             if (response != null) {                 responseString = String.valueOf(response.statusCode);                 // can get more details such as response.headers             }             return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));         }     };      requestQueue.add(stringRequest); } catch (JSONException e) {     e.printStackTrace(); } 
like image 145
BNK Avatar answered Sep 22 '22 14:09

BNK


I liked this one, but it is sending JSON not string as requested in the question, reposting the code here, in case the original github got removed or changed, and this one found to be useful by someone.

public static void postNewComment(Context context,final UserAccount userAccount,final String comment,final int blogId,final int postId){     mPostCommentResponse.requestStarted();     RequestQueue queue = Volley.newRequestQueue(context);     StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {         @Override         public void onResponse(String response) {             mPostCommentResponse.requestCompleted();         }     }, new Response.ErrorListener() {         @Override         public void onErrorResponse(VolleyError error) {             mPostCommentResponse.requestEndedWithError(error);         }     }){         @Override         protected Map<String,String> getParams(){             Map<String,String> params = new HashMap<String, String>();             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<String, String> getHeaders() throws AuthFailureError {             Map<String,String> params = new HashMap<String, String>();             params.put("Content-Type","application/x-www-form-urlencoded");             return params;         }     };     queue.add(sr); }  public interface PostCommentResponseListener {     public void requestStarted();     public void requestCompleted();     public void requestEndedWithError(VolleyError error); } 
like image 25
Hasan A Yousef Avatar answered Sep 21 '22 14:09

Hasan A Yousef