Skip to content

Instantly share code, notes, and snippets.

@mombrea
Last active May 24, 2023 10:58
Show Gist options
  • Star 73 You must be signed in to star a gist
  • Fork 34 You must be signed in to fork a gist
  • Save mombrea/7250835 to your computer and use it in GitHub Desktop.
Save mombrea/7250835 to your computer and use it in GitHub Desktop.
Example of performing a POST request using Google Volley for Android
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);
}
@prabinshrestha
Copy link

Can we do the same with JSONObjectRequest

@hackaprende
Copy link

What about sending an array of objects, like a JSONArray when you post a JSONObject?

@KingsleyUsoroeno
Copy link

I have a question why are we starting with a StringResquest is it based on the Api you are using or what and what if you would love to get a request back from the server how would you go about doing that

@christineadams990
Copy link

Your clear explanation really helped me understand. Thanks for the post!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment