Kaustubh
Kaustubh

Reputation: 653

Android : Sending form-data as body Google Volley

In my Android application, I am using google's volley for network operations. There is a case where I need to make a request but send body as form-data. I have tried everything else, but I am not able to make the request as form-data.

Here is a curl

curl -X POST -H "Content-Type: multipart/form-data" -F "mobile_number=<XXXX>" "<server_url>"

How can I achieve that -F part in volley? The Server is throwing bad request.

This is what I have done :

final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, URLFactory.OTP_URL,
                null, listener, errorListener){

            @Override
            public byte[] getBody() {
                final JSONObject  jsonObject = new JSONObject();
                try {
                    jsonObject.put("mobile_number", mobileNumber);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
                return jsonObject.toString().getBytes();
            }


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

Please help me in this.

Upvotes: 2

Views: 5510

Answers (1)

Arpit Ratan
Arpit Ratan

Reputation: 3026

This can be done in volley by creating the postBody yourself. Please refer the below code.

Code for creating the body:

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

        return sbPost.toString();
    }

Modifed getBody() code :

  @Override
            public byte[] getBody() {
                Map<String,String> params = new HashMap<>();
                params.add("mobile_number", mobileNumber);
                String postBody = createPostBody(params);

                return postBody.getBytes();
            }

You will need to modify 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;
            }

Upvotes: 2

Related Questions