简体   繁体   中英

How to upload video as multipart request using OkHTTP? [ Android ]

I need to upload video to an API, and this is how I've implemented the OKHTTP request:

 private void makeRequest(Uri uri)
{
    pr1.show();

    try
    {
        String path = uri.toString();
        Log.e("PATH",path);
        File file = new File(new URI(path));
        try {

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),
                            RequestBody.create(MediaType.parse("video/mp4"), file))
                    .addFormDataPart("title", "damn")
                    .build();

            Request request = new Request.Builder()
                    .url(URL)
                    .header("SproutVideo-Api-Key","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                    .post(requestBody)
                    .build();

            client.newCall(request)
                    .enqueue(new Callback() {
                        @Override
                        public void onFailure(final Call call, IOException e)
                        {

                        }

                        @Override
                        public void onResponse(Call call, final Response response) throws IOException {
                            String res = response.body().string();
                            Log.e("SUCCESS",""+res);
                            pr1.dismiss();


                        }
                    });


        } catch (Exception ex) {
            // Handle the error
        }
    }
    catch (Exception e){}

}

However, I am unable to complete a successful request.

Log at this line Log.e("PATH",path); shows :

content://com.android.providers.media.documents/document/video%3A75611

And when I add a line break at this line : client.newCall(request) , and run the debugger, the app doesn't end at any point, so I assume the request is not getting completed. What is possibly causing this? Is this the correct way of implementation?

I'm not familiar with the OkHTTP library, but one thing I noticed that will cause a problem is that the field for the video should be source_video , not file as outlined here .

You might also want to add some logging to your catch statements to see what, if anything might be failing silently since you seem to be ignoring any potential failures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM