2

I am using Retrofit for download APK file from the server.

Below is code snippet.

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Util.APK_DOWNLOAD_URL)
                .build();

        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);

        Call<ResponseBody> request = retrofitInterface.downloadFile();
        try {

            downloadFile(request.execute().body());

        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();

        }

And

public interface RetrofitInterface {

    @GET("development/filename.apk")
    @Streaming
    Call<ResponseBody> downloadFile();
}

But there is problem.

Download APK is always different. So

How can I set Some public static String in

@GET(Utils.APK_FILE_NAME)

And in my Utils class

public static String APK_FILE_NAME = ""

Currently I am getting

Attribute Value Must be Constant

Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
  • 2
    Possible duplicate of [Retrofit 2 - Dynamic URL](https://stackoverflow.com/questions/32559333/retrofit-2-dynamic-url) – Héctor Dec 07 '17 at 08:11

3 Answers3

5

you can use @Path annotation for example:

@GET("development/{filename}")
@Streaming
Call<ResponseBody> downloadFile(@Path("filename") String filename;

and

String filename;
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Util.APK_DOWNLOAD_URL)
                .build();

        RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);

        Call<ResponseBody> request = retrofitInterface.downloadFile(filename);
        try {

            downloadFile(request.execute().body());

        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();

        }
Lalit Kushwah
  • 3,861
  • 5
  • 25
  • 40
1

You can make it dynamic by passing it as parameter instead of declaring it at annotation as in

public interface RetrofitInterface {
    @Streaming
    Call<ResponseBody> downloadFile(@Url String filename);
}

Now you can access it at run time using

 Call<ResponseBody> request = retrofitInterface.downloadFile(Utils.APK_FILE_NAME);
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
  • Exception Occurred. Fatal Exception: java.lang.IllegalArgumentException HTTP method annotation is required (e.g., GET, POST, etc.). for method RetrofitInterface.downloadFile – Chirag Savsani Dec 07 '17 at 11:49
1

one way to pass string is using @Path annotation:

public interface RetrofitInterface {
  @GET("{APK_FILE_NAME}")
  Call<Users> getUsers(@Path(value = "APK_FILE_NAME", encoded = true) String apk_file_name);
}

For more detail use following link, https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Path.html