首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绕过Retrofit的"baseUrl必须以/结尾“

问绕过Retrofit的"baseUrl必须以/结尾“
EN

Stack Overflow用户
提问于 2017-11-16 14:06:53
回答 1查看 1.2K关注 0票数 0

我使用Retrofit 2.3.0与OAI-PMH端点进行交互.

现在,我碰巧与一个端点交互,它挑剔地判断它的基本URL是否以斜杠结尾:

没有斜线的:

http://www.relacionesinternacionales.info/ojs/oai.html?verb=Identify按预期工作。

用斜杠:

http://www.relacionesinternacionales.info/ojs/oai.html/?verb=Identify会导致重定向到404页。

现在的问题是Retroeft2.3.0要求基本URL以斜杠结尾。

为Retrofit构建器提供无尾斜杠基URL使Retrofit抱怨。

向Retrofit生成器提供以-a-斜杠结尾的基URL会导致Retrofit生成一个错误的URL,从而导致404错误。

我怎样才能绕过这个限制呢?

EN

回答 1

Stack Overflow用户

发布于 2017-11-16 15:36:27

作为解决办法,我使用Java来操作Retrofit对象的baseUrl字段。

首先,代码检查提供的baseUrl是否以斜杠结尾。如果是这样,就没有什么特别的事情要发生了。

如果提供的baseUrl不以斜杠结尾,则首先用尾随斜杠创建retrofit对象到baseUrl,然后将该baseUrl对象替换为原始的无斜杠结束baseUrl:

代码语言:javascript
复制
String baseUrl = "..."; // can end with slash or not

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl( baseUrl.endsWith("/") ? baseUrl : baseUrl + "/" )
        .addConverterFactory(ScalarsConverterFactory.create())
        .build();

// workaround for https://stackoverflow.com/q/47331753/923560
if ( ! baseUrl.endsWith("/") ) {
    try {
        Field baseUrlField = retrofit.getClass().getDeclaredField("baseUrl");
        baseUrlField.setAccessible(true);
        HttpUrl newHttpUrl = HttpUrl.parse(baseUrl);
        baseUrlField.set(retrofit, newHttpUrl);
        baseUrlField.setAccessible(false);
    }
    catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        LOG.error("Exception while manipulating baseUrl=" + baseUrl + " to not end with a slash", e);
        throw new RuntimeException(e);
    }
}

service = retrofit.create(OaiPmhService.class);
// ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47331753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档