Better follow redirection for HTTPClient by AgainPsychoX · Pull Request #7157 · esp8266/Arduino (original) (raw)

Solves #7156

First commit adds way to force follow redirections. The RFC document does not allow to redirect request with methods other than GET/HEAD without any user confirmation. To workaround that, and there is now setFollowRedirects(followRedirects_t follow) which allow library user to choose between following redirects as RFC allow without user confirmation (default); or force redirects - as user confirmed the redirection. There is still setFollowRedirects(bool follow) left, marked as deprecated.

Second commit makes the client follow most other implementations about 302 HTTP code (Found (1.1), previously Moved temporarily (1.0)). As mentioned already in the RFC:

Note: RFC 1945 and RFC 2068 specify that the client is not allowed
      to change the method on the redirected request.  However, **most
      existing user agent implementations treat 302 as if it were a 303
      response**, performing a GET on the Location field-value regardless
      of the original request method. The status codes 303 and 307 have
      been added for servers that wish to make unambiguously clear which
      kind of reaction is expected of the client.

This behavior is required in some cases, even in modern world. My today's example: Google Scripts Apps endpoint. I have POST handler setup to run some macro. It should response with JSON containing number of affected rows, but the server handle first POST request (execute macro) and response with redirect request with 302 and other location. Then my code needs to GET from the other location. By browsers (Chrome&Firefox) it works just nicely - as they understand 302 "correctly" (well, not in terms of HTTP 1.0). This commit brings this important behavior to the library.

Also, there is a small rewrite of sendRequest code just to make it more clear, without do {} while();. Used recursion - as it was also used in other parts. There is only one int in this whole function declared, so I think its fine.