android - 使用retrofit 2.0下载文件

时间:2017-11-15 12:18:54

标签: android retrofit2 downloading

我正在使用retrofit 2.0下载文件。问题是没有调用enqueue方法。没有错误也没有捕获。什么都没发生,我的错误在哪里?

这是我的界面:

public interface ApiService {

    @GET("uploads/{file_name}")
    Call<ServerResponse> downloadFile(@Path("file_name") String fileName);
}

这是我的下载代码:

private void downloadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.downloadFile(file.getName());
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

            }
        });
    }

2 个答案:

答案 0 :(得分:0)

可能你指的是方法&#34; enqueue()&#34;被称为,但它不是onResponse。

请等一段时间(一分钟就好了)并确保调用onResponse或onFailure。

如果您想了解更多信息,可以使用HTTP logging interceptor

答案 1 :(得分:0)

@POST("uploads/{file_name}")
    Observable<Document> getDocumentsList(@Path("file_name") String fileName);

并且代码webservice调用应该是

 Observable<Document> listObservable = mApiService.getDocumentsList(path);
    subscribe(listObservable, new Consumer<Document>() {
        @Override
        public void accept(Document resourceDtos) throws Exception {
            fillDocs(resourceDtos.getData());
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            fillDocs(throwable.getMessage());
        }
    });