Posting form-data Parameters in the body using Volley
Asked Answered
S

1

14

This is the Post Request done using postman

enter image description here

The response I want to get is :

    {
  "result": "success",
  "reason": {
    "first_name": "aswath",
    "last_name": "AsH",
    "email": "[email protected]",
    "phone": "\"8867336754\"",
    "authy_id": "26829982",
    "updated_at": "2016-09-27 06:38:07",
    "created_at": "2016-09-27 06:38:07",
    "id": "5012"
  },
  "sms": "token sent"
}

This is the Request I am trying to send :

 JSONObject jsonBody = new JSONObject();
        jsonBody.put("first_name", firstname);
        jsonBody.put("last_name", lastName);
        jsonBody.put("email", Email);
        jsonBody.put("phone", number);

        final String mRequestBody = jsonBody.toString();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.i("VOLLEY", response);
                Log.d("**********", "FETCHING IN VOLLEY REQ" + response.toString());


            }
        }, 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 mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                } catch (UnsupportedEncodingException uee) {
                    VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                    return null;
                }
            }


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

        getRequestOtpPage().addToRequestQueue(stringRequest);

But when i post request it returns the error!

How to solve the problem?

Sitnik answered 27/9, 2016 at 6:45 Comment(6)
Try implementing getParams() and pass simple key value pair instead of json objectMunson
Tried it , Error response is received. all the datas sent were correct.Sitnik
Remove getHeaders() method and then try.Munson
#39610276 Try this and make something general which will help you to achieve what you wantSnashall
check this one #28344948Shaer
or Use "Content-Type", "application/json" only instead of" Content-Type", "multipart/form-data" in getHeaders() method because you didn't require multipart typeMunson
S
22

Just try with below code this will use to send simple post data using volley, just replace URL and parameter data.

StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                        }
                    }){
                @Override
                protected Map<String,String> getParams(){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put(KEY_USERNAME,username);
                    params.put(KEY_PASSWORD,password);
                    params.put(KEY_EMAIL, email);
                    return params;
                }

            };

            getRequestOtpPage().addToRequestQueue(stringRequest);
Sextuple answered 27/9, 2016 at 7:10 Comment(8)
Why its not working with JsonObjectRequest but with StringRequest?Conchiolin
@QadirHussain i have same question, volley creator should answer this.Vaporization
if basic auth is need where I put basic auth?Lenz
@Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> params = new HashMap<String, String>(); String creds = String.format("%s:%s","USERNAME","PASSWORD"); String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT); params.put("Authorization", auth); return params; }Sextuple
you can add getHeaders() meathod for adding header in requestSextuple
how to send image also as formdata?Pratfall
you can pass image as base64 string in formdata, if you want pass image as file then you have to use multipart entity class.Sextuple
The Question was about how to pass data in request body. and you answered what?Gamester

© 2022 - 2024 — McMap. All rights reserved.