Proper behavior for clients receiving status 307

549 Views Asked by At

I've been using OkHttp for hitting Nest's Firebase API (I don't like the Firebase SDK since it keeps a socket open, which is power hungry for my purposes). On several of the requests, I'll get a status code 307 to redirect to another URL. This isn't terribly surprising. What is surprising is that OkHttp doesn't follow the redirect even if I call client.setFollowRedirects(true) and/or client.setFollowSSLRedirects(true) both of which default to true anyway.

I've copied my version of a doPut() method below. If the recursive call isn't there, often times the attempt will do nothing. I'm wondering whether Firebase is using the wrong status code, OkHttp isn't interpreting it correctly, or if this is the correct way to handle this situation. It seems like something is wrong here, but I'm not sure what.

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();
}
1

There are 1 best solutions below

0
On BEST ANSWER

There's nothing in OkHttp that handles a redirect while keeping the POST method. This might be a mistake in our design. In the interim, you can work around by handling the redirect in an interceptor. You can use the code you've already written as a starting point; the interceptors doc may also help.