我一直在使用 OkHttp 访问 Nest 的 Firebase API(我不喜欢 Firebase SDK,因为它会保持套接字打开,这对我来说非常耗电)。在几个请求中,我将获得状态代码 307 以重定向到另一个 URL。这并不奇怪。 令人惊讶的是 OkHttp 不遵循重定向,即使我调用 client.setFollowRedirects(true)
和/或 client.setFollowSSLRedirects(true)
两者都默认为 true
。
我在下面复制了我的 doPut()
方法版本。如果递归调用不存在,则尝试通常不会执行任何操作。我想知道 Firebase 是否使用了错误的状态代码,OkHttp 是否没有正确解释它,或者这是否是处理这种情况的正确方法。好像这里出了点问题,但我不确定是什么。
public static String doPut(String url, String body, String contentType) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody =
RequestBody.create(MediaType.parse(contentType), body);
Request request = new Request.Builder().url(url).put(requestBody).build();
Response response = client.newCall(request).execute();
if (response.code() == 307) {
doPut(response.header("Location"), body, contentType);
}
return response.body().string();
}
最佳答案
OkHttp 中没有任何东西可以在保留 POST 方法的同时处理重定向。这可能是我们设计中的一个错误。在此期间,您可以通过在拦截器中处理重定向来解决问题。您可以使用已经编写的代码作为起点; interceptors doc也可能有所帮助。
关于android - 客户端接收状态 307 的正确行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31023468/