Retrofit 2 file down/upload

前端 未结 5 1756
栀梦
栀梦 2020-12-13 00:54

I\'m trying to down/upload a file with retrofit 2 but can\'t find any tutorials examples on how to do so. My code for downloading is:

@GET(\"documents/checko         


        
5条回答
  •  不知归路
    2020-12-13 01:12

    For downloading, you can use ResponseBody as your return type --

    @GET("documents/checkout")
    @Streaming
    public Call checkout(@Query("documentUrl") String documentUrl, @Query("accessToken") String accessToken, @Query("readOnly") boolean readOnly);
    

    and you can get the ResponseBody input stream in your call back --

    Call call = RetrofitSingleton.getInstance(serverAddress)
                .checkout(document.getContentUrl(), apiToken, readOnly[i]);
    
    call.enqueue(new Callback() {
            @Override
            public void onResponse(Response response,
                    Retrofit retrofit) {
                String fileName = document.getFileName();
                try {
                    InputStream input = response.body().byteStream();
                    //  rest of your code
    

    Your upload looks okay at first glance if you server handles multipart messages correctly. Is it working? If not, can you explain the failure mode? You also might be able to simplify by not making it multipart. Remove the @Multipart annotation and convert @Path to @Body --

    @POST("documents/checkin")
    public Call checkin(@Query("documentId") String documentId, @Query("name") String fileName, @Query("accessToken") String accessToken, @Body RequestBody file);
    

提交回复
热议问题