Member-only story
How to Specify the Retrofit Request
If you’re reading this and you haven’t written code for any Retrofit requests yet, please check our previous blog posts to get started. For all you Retrofit experts: the request declaration for downloading files looks almost like any other request:
// option 1: a resource relative to your base URL
@GET("/resource/example.zip")
Call<ResponseBody> downloadFileWithFixedUrl();
// option 2: using a dynamic URL
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);
If the file you want to download is a static resource (always at the same spot on the server) and on the server your base URL refers to, you can use option 1. As you can see, it looks like a regular Retrofit 2 request declaration. Please note, that we’re specifying ResponseBody
as return type. You should not use anything else here, otherwise Retrofit will try to parse and convert it, which doesn't make sense when you're downloading a file.
The second option is new to Retrofit 2. You can now easily pass a dynamic value as full URL to the request call. This can be especially helpful when downloading files, which are dependent of a parameter, user or time. You can build the URL during runtime and request the exact file without any hacks…