HttpURLConnection redirects my POST request into a GET
Asked Answered
B

2

6

I'm sending a HttpURLConnection with setInstanceFollowRedirects(true) and POST, get a redirect response that looks like this:

HTTP/1.1 302 Found
Server: nginx
Date: Wed, 09 Jan 2013 20:47:56 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Status: 302 Found
Status: 301 Moved Permanently
Location: http://foo.bar/...

And the next request that the JVM sends is a GET request (to the correct, redirected URL). It also seems to drop one of the HTTP headers I added to the original request.

FYI, I'm not using HttpURLConnection directly, but rather through Play Framework's WS wrapper.

My question is - is this a known issue with Java (Sun JVM 1.7.0)? Or could it be a bug in Play Framework?

Baldhead answered 9/1, 2013 at 21:11 Comment(2)
I assume it's on purpose, as common browsers will do the same.Misfit
@JulianReschke - I'm implementing an API client, and this completely breaks it.Baldhead
T
8

This is the default behavior of Java. You can change it by setting the system property http.strictPostRedirect=true.

For details, please see this quote from the Java source HttpURLConnection implementation source:

    /* The HTTP/1.1 spec says that a redirect from a POST 
     * *should not* be immediately turned into a GET, and
     * that some HTTP/1.0 clients incorrectly did this.
     * Correct behavior redirects a POST to another POST.
     * Unfortunately, since most browsers have this incorrect
     * behavior, the web works this way now.  Typical usage
     * seems to be:
     *   POST a login code or passwd to a web page.
     *   after validation, the server redirects to another
     *     (welcome) page
     *   The second request is (erroneously) expected to be GET
     * 
     * We will do the incorrect thing (POST-->GET) by default.
     * We will provide the capability to do the "right" thing
     * (POST-->POST) by a system property, "http.strictPostRedirect=true"
     */
Tharp answered 10/1, 2013 at 10:47 Comment(0)
M
0

An alternative, assuming you control the server: use status code 307.

Misfit answered 10/1, 2013 at 12:13 Comment(2)
Didn't work for me, it still redirects to a GET request.Dandelion
Sounds like a Java bug then.Misfit

© 2022 - 2024 — McMap. All rights reserved.