【问题标题】:Retrofit 2 removes characters after hostname from base urlRetrofit 2 从基本 url 中删除主机名后的字符
【发布时间】:2015-11-27 21:40:19
【问题描述】:

我正在使用 Retrofit 来访问 RESTful api。基本网址是:

http://api.example.com/service

这是接口的代码:

public interface ExampleService {
    @Headers("Accept: Application/JSON")
    @POST("/album/featured-albums")
    Call<List<Album>> listFeaturedAlbums();
}

这就是我发送请求和接收响应的方式:

new AsyncTask<Void, Void, Response<List<Album>>>() {

        @Override
        protected Response<List<Album>> doInBackground(Void... params) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://api.example.com/service")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            ExampleService service = retrofit.create(ExampleService.class);

            try {
                return service.listFeaturedAlbums().execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Response<List<Album>> listCall) {
            Log.v("Example", listCall.raw().toString());
        }
    }.execute();

我得到的日志很奇怪:

V/示例:响应{protocol=http/1.1, code=404, message=Not Found, url=http://api.example.com/album/featured-albums}

这是怎么回事?

【问题讨论】:

  • 你能解决这个问题吗?因为我也面临同样的问题。即使我尝试了正确的答案,我总是会失败

标签: android retrofit


【解决方案1】:

Retrofit 2 使用与 &lt;a href=""&gt; 相同的规则。

相对 URL 上的前导 / 告诉 Retrofit 它是主机上的绝对路径。这是我提供的演示文稿中的一个示例:

注意在底部解析的错误 URL。

通过删除前导的/,URL 将变为相对的,并将与作为基本 URL 一部分的路径段结合。在演示文稿中更正了最终 URL 现在是正确的:

在您的示例中,基本 URL 上没有尾随 /。您可能想要添加一个,以便在它之上解析相对路径,而不是作为它的兄弟。

【讨论】:

  • 我真的不明白为什么这种新型的 URL 解析更有益。您可以从中得到的只是隐藏的错误(如this question所示)和反直觉的结果(http://api.example.com/service + /album/featured-albums 不是http://api.example.com/album/featured-albums)。而这个无声的错误除了您将/ 放在基本网址的末尾还是API URL 的前面之外,什么都没有。有没有这种截断有用的用例?
  • 看完演示后我觉得很有意义,但是在网站上添加一个小注释会很棒。我花了几分钟才发现出了什么问题。
  • @JakeWharton 我如何@POSTbaseUrl(不添加任何pathSegments?示例:baseUrlhttp://api.example.com/album/featured-albums,我希望我的@POST 呼叫转到http://api.example.com/album/featured-albums(与基本 URL 相同)。@POST("") 抛出 java.lang.IllegalArgumentException: Missing either @POST URL or @Url parameter.
  • 使用@Post(".")
猜你喜欢
  • 2019-08-21
  • 2019-04-25
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
相关资源
最近更新 更多