Retrofit 2从主URL删除主机名后的字符

Ash*_*lak 113 android retrofit

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

http://api.example.com/service

这是界面的代码:

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

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

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();
Run Code Online (Sandbox Code Playgroud)

我得到的日志是奇怪的事情:

V /示例:响应{protocol = http/1.1,代码= 404,消息=未找到,url = http://api.example.com/album/featured-albums }

这里发生了什么?

Jak*_*ton 260

Retrofit 2使用相同的规则<a href="">.

/相对URL 的前导告诉Retrofit它是主机上的绝对路径.以下是我给出的演示文稿的示例:

在此输入图像描述

请注意底部已解决的错误网址.

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

在此输入图像描述

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

  • 使用`@Post(".")` (14认同)
  • 看完演示文稿后对我来说很有意义,但在网站上添加一个小注释会很棒.我花了几分钟才发现出了什么问题. (11认同)
  • 我真的不明白为什么这种新型的URL解析更有益.所有你能从中得到的是隐藏的错误(如这个问题所示),反直觉的结果(`http:// api.example.com/service` +`/ album/featured-albums`不是`http: // api.example.com/album/featured-albums`).这个无声错误源于无论你是将`/`放在基本URL的末尾还是放在API URL的前面.是否存在截断有用的用例? (8认同)
  • @JakeWharton我如何`@ POST`到`baseUrl`(没有添加任何`pathSegment`s?例如:`baseUrl`是`http:// api.example.com/album/featured-albums`我希望我的`@ POST`调用转到`http:// api.example.com/album/featured-albums`(与基地相同的URL).` @ POST("")`抛出`java.lang.IllegalArgumentException:Missing @POST URL或@Url参数 (8认同)
  • [这是演示视频](https://youtu.be/KIAoQbAu3eA?t=32m19s) (3认同)