使用retrofit2上传视频

时间:2017-06-02 00:27:55

标签: android retrofit2

我正在尝试使用Retrofit2将视频从Android设备上传到服务器,最终得到错误'400 Bad Request'。以下是实施。有人可以帮忙解决错误吗?

public interface RetrofitService {
/**
 * Upload Videos to Server
 */
@Multipart
@POST("store/S3")
Call<ResponseBody> uploadToServer(@Query("key") String ServerAPI,
                                      @Query("mimetype") String videoMimeType,
                                      @Query("path") String path,
                                      @Query("container") String container,
                                      @Query("policy") String policy,
                                      @Query("signature") String signature,
                                      @Part MultipartBody.Part video,
                                      @Part("type") String videoType,
                                      @Part("name") String videoName );

}

helper.java中的客户端实现

  private void uploadVideos(String videUri, String policy, String signature){
    String BASE_URL = "https://www.example.com/api/";
    String EXAMPLE_API_KEY = "xebfc";
    String mimeType = "video/mp4";
    String path = "mezzanine_videos/";
    String container = S3_BUCKET;

    // use the FileUtils to get the actual file by uri
    File videoFile = new File(videoUri);

    // create RequestBody instance from file
    RequestBody videoBody = RequestBody.create(MediaType.parse("video/*"), videoFile);

    // MultipartBody.Part is used to send the actual file
    MultipartBody.Part vFile = MultipartBody.Part.createFormData("video", videoFile.getName(), videoBody);

    String videoType = "video/mp4";
    String videoName = "video.mp4";

    final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    RetrofitService service = retrofit.create(RetrofitService.class);
    Call<ResponseBody> call = service.uploadToServer( EXAMPLE_API_KEY, mimeType, path, container, policy, signature, vFile, videoType, videoName);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d("Response", "Successful Response");
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("Response", "Failure Response");
        }
    }); }

服务器实现工作正常,因为我通过执行如下的卷曲帖子获得了有效的响应。

curl -X POST -F fileUpload=@animation.mov "https://www.example.com/api/store/S3?key= xebfc&mimetype=video%2Fmp4&path=mezzanine_videos/&container= S3_BUCKET&policy=ppppp&signature=ssss

1 个答案:

答案 0 :(得分:0)

在对MultipartBody.Part.createFormData进行一些调试之后,发现该名称与我的后端实现不匹配。下面的代码解决了这个问题。

useDelimiter

其余代码与上面提到的相同。