2017-06-02 185 views
0

我想使用Retrofit2將視頻從android設備上傳到服務器,最終得到錯誤「400錯誤請求」。以下是實施。有人可以幫助解決這個錯誤嗎?在helper.java使用retrofit2上傳視頻

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); 

}

客戶implemetation因爲我得到這樣的捲曲後像下面的有效響應

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"); 
     } 
    }); } 

Server實現正常工作。

curl -X POST -F [email protected] "https://www.example.com/api/store/S3?key= xebfc&mimetype=video%2Fmp4&path=mezzanine_videos/&container= S3_BUCKET&policy=ppppp&signature=ssss 
+0

將日誌攔截器添加到您的翻新實例並更新問題。您是否確定使用MediaType.parse(「video/*」)而不是確切類型和''video'作爲部件的名稱? –

+0

感謝您的回覆@KonstantinBerkow,MediaType.parse(「video/*」)或MediaType.parse (「video」)導致同樣的錯誤,我將添加一些格式化的日誌記錄攔截器。 – Babs

回答

0

上MultipartBody.Part.createFormData一些調試後,想通了,這個名字不是我的後端實現匹配。下面的代碼解決了問題。

MultipartBody.Part vFile = MultipartBody.Part.createFormData("fileUpload", videoFile.getName(), fileBody); 

其餘代碼與上面提到的相同。