HttpURLConnection将我的POST请求重定向到GET

时间:2013-01-09 21:11:04

标签: java http playframework httpurlconnection playframework-1.x

我正在发送HttpURLConnection setInstanceFollowRedirects(true)POST,获得如下所示的重定向回复:

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/...

JVM发送的下一个请求是GET请求(到正确的重定向URL)。它似乎也删除了我添加到原始请求中的一个HTTP头。

仅供参考,我不是直接使用HttpURLConnection,而是通过Play Framework的WS包装器。

我的问题是 - 这是Java(Sun JVM 1.7.0)的已知问题吗?或者它可能是Play Framework中的错误吗?

2 个答案:

答案 0 :(得分:5)

这是Java的默认行为。您可以通过设置系统属性http.strictPostRedirect = true来更改它。

有关详细信息,请参阅Java源代码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"
     */

答案 1 :(得分:0)

另一种方法,假设您控制服务器:使用状态代码307。