【问题标题】:Retrofit GET without a value in Android改造 GET 在 Android 中没有值
【发布时间】:2015-11-04 22:06:15
【问题描述】:

我在大多数调用中都使用 Retrofit,但在其中一种情况下,我在参数中提供了完整路径。我的网址是这样的http://www.example.com/android.json。此 URL 已完整提供,因此我必须在运行时对其进行路径。我按照这里的建议实现端点 https://medium.com/@kevintcoughlin/dynamic-endpoints-with-retrofit-a1f4229f4a8d 但在@GET 中,我需要能够输入@GET("")。这不起作用,因为我收到一条错误消息说我应该提供至少一个“/”。

如果我添加斜杠,则 URL 变为 http://www.example.com/android.json/ 并且它不起作用,服务器返回禁止。我还尝试创建一个自定义的GET 接口,类似于这里的https://github.com/square/retrofit/issues/458,但使用GET,并且没有在接口中提供值方法。然后我收到另一个错误,提示缺少值。

基本上我需要能够提供空值或空值,但改造不允许这样做。我该如何解决这个问题?现在我正在手动执行 JSON 请求,但有没有一种方法可以在这种情况下使用改造?我需要传递完整的 URL,我无法做到端点 http://www.example.com@GET("/android.json")。 谢谢

【问题讨论】:

标签: android json get retrofit retrofit2


【解决方案1】:

您可以使用 @GET(".") 表示您的 url 与基本 url 相同。

@GET(".")
Observable<Result> getData(@Query("param") String parameter);

【讨论】:

    【解决方案2】:

    我尝试了this 方法,但对我不起作用。

    此问题的解决方法是:

    //Retrofit interface
    public interface TestResourceClient {
        @GET
        Observable<Something> getSomething(@Url String anEmptyString);
    }
    
    //client call
    Retrofit.Builder().baseUrl("absolute URL").build()
    .create(TestResourceClient.class).getSomething("");
    

    此解决方案的缺点是您必须在 getSomething("") 方法调用中提供空字符串。

    【讨论】:

      【解决方案3】:

      我在 Retrofit 2 中遇到了同样的问题。使用 @GET@GET("")@GET(".") 并没有解决我的问题。

      根据official document,您可以使用相同的baseUrl@GET 参数。

      端点值可能是完整的 URL。

      具有主机的值替换 baseUrl 的主机,并且具有方案的值也替换 baseUrl 的方案。
      基本网址:http://example.com/
      端点:https://github.com/square/retrofit/
      结果:https://github.com/square/retrofit/

      所以在我的情况下:

      interface MyAPI {
          @GET("http://www.omdbapi.com/")
          suspend fun getMovies(
              @Query("apikey") apikey: String,
              @Query("s") s: String
          ): Response<MoviesResponse>
      
          companion object {
              operator fun invoke(): MyAPI {
                  return Retrofit.Builder()
                      .addConverterFactory(GsonConverterFactory.create())
                      .baseUrl("http://www.omdbapi.com/")
                      .build()
                      .create(MyAPI::class.java)
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-01-16
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 2023-01-22
        • 2016-12-22
        相关资源
        最近更新 更多