【问题标题】:How to change Value dynamically in @GET annotation?如何在@GET 注释中动态更改值?
【发布时间】:2018-05-21 06:50:17
【问题描述】:

我正在使用Retrofit从服务器下载APK文件。

下面是代码sn-p。

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

        }

还有

public interface RetrofitInterface {

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

但是有问题。

下载的 APK 总是不同的。 所以

我怎样才能设置一些public static String in

@GET(Utils.APK_FILE_NAME)

在我的 Utils 类中

public static String APK_FILE_NAME = ""

目前我正在接受

属性值必须是常数

【问题讨论】:

标签: android annotations retrofit


【解决方案1】:

你可以使用@Path注解例如:

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

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

        }

【讨论】:

    【解决方案2】:

    您可以通过将其作为参数传递而不是像在注释中那样声明它来使其动态化

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

    现在您可以在运行时使用

     Call<ResponseBody> request = retrofitInterface.downloadFile(Utils.APK_FILE_NAME);
    

    【讨论】:

    • 发生异常。致命异常:java.lang.IllegalArgumentException 需要 HTTP 方法注释(例如,GET、POST 等)。对于方法 RetrofitInterface.downloadFile
    【解决方案3】:

    传递字符串的一种方法是使用@Path 注解:

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

    更多详情请使用以下链接, https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Path.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多