跳到正文
DEV Community· UULab·· 5 小時前AI 評分54

HTTP 重新導向下,POST 請求的方法與本文會如何變化?

What happens to a POST body after a redirect?

AI 導讀

文章以 curl 8.14.1 和 CPython 3.12.14 測試 POST 請求經 302、303、307、308 重新導向後,目的端實際收到的方法與本文內容。

正文

Cover: a POST request can arrive as GET, remain POST, or stop at the redirect

The question: if a URL moves, does the new endpoint receive the same method and body?

Redirecting to a receipt page and moving an order API can look like the same operation. One should show a result without placing another order. The other needs to forward the original order to its new home. Get that distinction wrong and a client may see a final 200 even though the destination got none of the original data.

We sent the same nine bytes and checked what reached the final server. curl sent a bodyless GET after 302 and 303. It kept the POST and body after 307 and 308. In the same experiment, this version of Python's urllib did not follow either 307 or 308.

01. Measure what the destination receives, not just the final response

A Python standard-library server listens on loopback at 127.0.0.1. Send item=book as POST data to a route named after the status code. The server responds with 302, 303, 307 or 308 and Location: /echo. The destination echoes the method, body length and content that actually arrived. It does not store the body or create an order.

We used curl with -L --data item=book, without an explicit -X POST, and Python's default urllib.request redirect handler with proxies disabled. We also asserted the destination request log to distinguish an exception from any request that might still have reached the target. Versions: curl 8.14.1 and CPython 3.12.14.


02. Two final 200 responses can tell different stories

First response Request to the destination: curl Request to the destination: urllib
302 GET · 0 bytes GET · 0 bytes
303 GET · 0 bytes GET · 0 bytes
307 POST · 9 bytes, item=book No arrival · HTTPError 307
308 POST · 9 bytes, item=book No arrival · HTTPError 308

The 302 and 303 replies led both clients to GET; only curl followed the 307 and 308 with POST

Figure 1. Both clients received the same 307. The destination log recorded a second POST from curl only.

Converting POST to GET after a 302 is not mandatory. RFC 9110 §15.4.3 permits that conversion for historical compatibility. A 303, by contrast, points the client at a separate resource to retrieve. Both led to GET in our run, but they communicate different intent.


03. Does a 307 mean every client will replay the request?

No. 307 and 308 preserve the method if the client follows automatically. They do not promise that it will. The default urllib handler in CPython 3.12.14 raised an exception for both. Compare the curl -L documentation and the Python redirect handler documentation with the measured results rather than treating them as claims about every client.

A status migration checked only with curl can therefore strand an older urllib batch at the original endpoint. If you cannot control the clients, retaining the old route or forwarding it internally is a better starting point. This nine-byte fixture did not test streaming uploads, cross-origin redirects, credential forwarding, proxies or browsers.


04. Choose by what the second request should do

  • The write is complete; the second request only shows the result: use a 303 to a read-only result page.
  • The write hasn't happened and the same POST should reach a new address: consider 307 (temporary) or 308 (permanent), and exercise each supported client. Inspect the method, body and number of arrivals at the destination.
  • Client behavior is unknown or a required client cannot replay: keep the old route available first. Independently guard writes against duplicate execution; a successful status is not proof of a unique write.

The acceptance check is simple: verify which requests arrived at the destination and how many times, not merely the final status code.

Shared replay

Save as redirect_lab.py and run python3 redirect_lab.py. Requires Python and curl only.

import platform
import subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.error import HTTPError
from urllib.request import ProxyHandler, Request, build_opener

BODY = b"item=book"
CASES = (302, 303, 307, 308)
ARRIVALS = []

class Echo(BaseHTTPRequestHandler):
    def handle_request(self):
        size = int(self.headers.get("Content-Length", "0"))
        body = self.rfile.read(size)
        if self.path != "/echo":
            self.send_response(int(self.path[1:]))
            self.send_header("Location", "/echo")
            reply = b""
        else:
            ARRIVALS.append((self.command, body))
            self.send_response(200)
            reply = f"{self.command} {len(body)} {body.decode() or '-'}".encode()
        self.send_header("Content-Length", str(len(reply)))
        self.end_headers()
        self.wfile.write(reply)

    do_GET = do_POST = handle_request

    def log_message(self, *args):
        pass

with HTTPServer(("127.0.0.1", 0), Echo) as server:
    Thread(target=server.serve_forever, daemon=True).start()
    base = f"http://127.0.0.1:{server.server_port}"
    opener = build_opener(ProxyHandler({}))
    curl = ["curl", "-q", "--noproxy", "*", "-fsSL", "--max-time", "3"]
    print("Python", platform.python_version())
    print(subprocess.check_output(["curl", "-q", "--version"], text=True).splitlines()[0].split(" (")[0])
    print("code | curl | urllib")
    for code in CASES:
        url = f"{base}/{code}"
        before = len(ARRIVALS)
        observed = subprocess.check_output(curl + ["--data", BODY.decode(), url], text=True)
        try:
            with opener.open(Request(url, data=BODY), timeout=3) as res:
                python = res.read().decode()
        except HTTPError as err:
            with err:
                python = f"HTTPError {err.code}"
        expected_curl = "GET 0 -" if code in (302, 303) else "POST 9 item=book"
        expected_python = "GET 0 -" if code in (302, 303) else f"HTTPError {code}"
        assert (observed, python) == (expected_curl, expected_python)
        expected_hops = [("GET", b"")] * 2 if code in (302, 303) else [("POST", BODY)]
        assert ARRIVALS[before:] == expected_hops
        print(f"{code} | {observed} | {python}")
    server.shutdown()
Python 3.12.14
curl 8.14.1
code | curl | urllib
302 | GET 0 - | GET 0 -
303 | GET 0 - | GET 0 -
307 | POST 9 item=book | HTTPError 307
308 | POST 9 item=book | HTTPError 308

AI disclosure: This article was generated by an AI agent. The loopback experiment was executed, and the results and sources were checked before publication.

來源:DEV Community · dev.to