How to send Send form-urlencoded parameters in post request android volley?

By | June 30, 2017

We have to override the getBodyContentType() method in volley to enable “form-urlencoded parameters” in POST request using Volley.
Here is how the code will look like.

If you are not familiar with Volley, Checkout my post here on volley. It will give you a perfect picture on what Volley can do.

Code – Method 1

StringRequest jsonObjRequest = new StringRequest(Request.Method.POST,
		getResources().getString(R.string.base_url),
		new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				Log.i(TAG, "Success");
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				VolleyLog.d("volley", "Error: " + error.getMessage());
				error.printStackTrace();
				Log.e(TAG, "Success");
			}
		}) {

	@Override
	public String getBodyContentType() {
		return "application/x-www-form-urlencoded; charset=UTF-8";
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		Map<String, String> params = new HashMap<String, String>();
		params.put("username", edtUsername.getText().toString().trim());
		params.put("password", edtPwd.getText().toString().trim());
		return params;
	}

};

AppController.getInstance().addToRequestQueue(jsonObjRequest);


Here is another method for achieving the same thing.

Code – Method 2

createPostBody

We will create post body first where we will specify the encoding.

public static final String BOUNDARY = "ANY_STRING";

private String createPostBody(Map<String, String> params) {
	StringBuilder sb = new StringBuilder();
	for (String key : params.keySet()) {
		if (params.get(key) != null) {
			sb.append("\r\n" + "--" + BOUNDARY + "\r\n");
			sb.append("Content-Disposition: form-data; name=\"" 
                                   + key + "\"" + "\r\n\r\n");
			sb.append(params.get(key));
		}
	}

	return sbPost.toString();
}

Override the getBody() function

We will use the Post Body here in this function.

@Override
public byte[] getBody() {
	Map<String,String> params = new HashMap<>();
	params.add("user_id", userId);
	String postBody = createPostBody(params);
	return postBody.getBytes();
}

Override the getHeaders() function

You will need to override getHeaders() as well to tell the server what you boundary is :

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
	final HashMap<String, String> headers = new HashMap<>();
	headers.put("Content-Type", "multipart/form-data;boundary=" + BOUNDARY;);
	return headers;
}

Please post your comments here about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *