iluxa.b
iluxa.b

Reputation: 405

Upload files with Volley custom body post request

I need to send 2 files to a server using volley library in Android. There is an example of how it works well in Postman: example I need to reproduce this exactly POST call in android. Please take a look of my code for now (which is not working):

JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, URL, new JSONObject(params), new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Log.i("Response", response.toString());

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            Log.e("VOLLEY", error.toString());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put("Urine", "test");

            return params;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String,String> params = new HashMap<>();
            params.put("Authorization", "token");
            return params;
        }

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

        @Override
        public byte[] getBody() {
            int size = (int) file.length();
            byte[] bytes = new byte[size];
            try {
                BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
                buf.read(bytes, 0, bytes.length);
                buf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bytes;
        }

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            byte[] data = response.data;
            String message = new String(data);
            Log.i("parseNetworkResponse", String.valueOf(message));

            return super.parseNetworkResponse(response);
        }
    };

How can I implement this using Volley library? Thanks.

Upvotes: 0

Views: 826

Answers (1)

Ryan Godlonton-Shaw
Ryan Godlonton-Shaw

Reputation: 584

Retrofit 2 in my opinion has been a much better and easier library to work with for file uploading.

Here is a nice and easy tut to work through. It should assist you.

Retrofit 2 - Multifile Uploading

Upvotes: 3

Related Questions