我使用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错误。
我怎样才能绕过这个限制呢?
发布于 2017-11-16 15:36:27
作为解决办法,我使用Java来操作Retrofit对象的baseUrl字段。
首先,代码检查提供的baseUrl是否以斜杠结尾。如果是这样,就没有什么特别的事情要发生了。
如果提供的baseUrl不以斜杠结尾,则首先用尾随斜杠创建retrofit对象到baseUrl,然后将该baseUrl对象替换为原始的无斜杠结束baseUrl:
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);
// ...https://stackoverflow.com/questions/47331753
复制相似问题