Manuel Castro
Manuel Castro

Reputation: 1723

Send ByteArray with Android volley

There is any way to send a byte array with Volley?

Now I'm using this:

post.setEntity(new ByteArrayEntity(rawPacket.toByteArray()));
try {
    response = client.execute(post);
} catch (IOException e) {
    e.printStackTrace();
}

There is something like this in Volley? There is a method to pass custom object to send with the POST/GET request?

protected Map<String, String> getParams() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<>();
            params.put("RawPacket", rawPacket.toByteArray().toString());
            return params;
        }

I need something like protected Map<String, ByteArray> getParams()

Upvotes: 2

Views: 3920

Answers (2)

Manuel Castro
Manuel Castro

Reputation: 1723

I find the solution overriding the function public byte[] getBody() to send custom data, I should read better the documentation!

StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.example.com/",
    new Response.Listener<String>() {
      @Override
      public void onResponse(String response) {
      }
    }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
    }
  }) {
  @Override
  public byte[] getBody() throws AuthFailureError {
    return new byte[] {1, 2, 3, 4, 5};
  }

Upvotes: 4

Kevin Crain
Kevin Crain

Reputation: 1935

See code below:

public class JsonArrayRequest extends JsonRequest<JSONArray> {
/**
 * Creates a new request.
 * @param url URL to fetch the JSON from
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
}

You have to create a subclass of JsonRequest and use that instead.

See related link: Volley - Sending a POST request using JSONArrayRequest

Also might want to Base64 encode the bytes and add it to the JsonArray.

Upvotes: 0

Related Questions