Working POST Multipart Request with Volley and without HttpEntity

前端 未结 5 1339
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 09:55

This is not really a question, however, I would like to share some of my working code here for your reference when you need.

As we know that HttpEntity

5条回答
  •  逝去的感伤
    2020-11-22 10:12

    I found a wrapper of the original volley library which is easier to integrate for multi-part requests. It also supports uploading the multi-part data along with other request parameters. Hence I am sharing my code for the future developers who might run into the problem that I was having (i.e. uploading multi-part data using volley along with some other parameters).

    Add the following library in the build.gradle file.

    dependencies {
        compile 'dev.dworks.libs:volleyplus:+'
    }
    

    Please note that, I removed the original volley library from my build.gradle and used the above library instead which can handle both multi-part and normal requests having similar integration technique.

    Then I just had to write the following class which handles the POST request operation.

    public class POSTMediasTask {
        public void uploadMedia(final Context context, String filePath) {
    
            String url = getUrlForPOSTMedia(); // This is a dummy function which returns the POST url for you
            SimpleMultiPartRequest multiPartRequestWithParams = new SimpleMultiPartRequest(Request.Method.POST, url,
                    new Response.Listener() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("Response", response);
                            // TODO: Do something on success
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO: Handle your error here
                }
            });
    
            // Add the file here
            multiPartRequestWithParams.addFile("file", filePath);
    
            // Add the params here
            multiPartRequestWithParams.addStringParam("param1", "SomeParamValue1");
            multiPartRequestWithParams.addStringParam("param2", "SomeParamValue2");
    
            RequestQueue queue = Volley.newRequestQueue(context);
            queue.add(multiPartRequestWithParams);
        }
    }
    

    Now execute the task like the following.

    new POSTMediasTask().uploadMedia(context, mediaPath);
    

    You can upload one file at a time using this library. However, I could manage to upload multiple files, just by initiating multiple tasks.

    Hope that helps!

提交回复
热议问题