0

I'm using Volley as my http client library. i need to send payload raw data as part of the request with Volley? there are posts like: How to send Request payload to REST API in java?

but how this can be achieved using Volley?

Community
  • 1
  • 1
BoazGarty
  • 1,410
  • 4
  • 18
  • 38

2 Answers2

1

example:

    final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

check the source and more info here

**UPDATE: ** If you need to add params you can simply override getParams()

Example:

  @Override
protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
      params.put("param1", "val1");
      params.put("randomFieldFilledWithAwkwardCharacters","{{%stuffToBe Escaped/"); 
      return params;
    }

You don't need to override getBody yourself neither encode special chars as Volley is doing this for you.

kalin
  • 3,546
  • 2
  • 25
  • 31
1

need to use StringRequest as djodjo mentioned. also getBody method need to be override - taken from here Android Volley POST string in body

@Override
                public byte[] getBody() throws AuthFailureError {
                    String httpPostBody="your body as string";
                    // usually you'd have a field with some values you'd want to escape, you need to do it yourself if overriding getBody. here's how you do it
                    try {
                        httpPostBody=httpPostBody+"&randomFieldFilledWithAwkwardCharacters="+ URLEncoder.encode("{{%stuffToBe Escaped/","UTF-8");
                    } catch (UnsupportedEncodingException exception) {
                        Log.e("ERROR", "exception", exception);
                        // return null and don't pass any POST string if you encounter encoding error
                        return null;
                    }
                    return httpPostBody.getBytes();
                }
Community
  • 1
  • 1
BoazGarty
  • 1,410
  • 4
  • 18
  • 38