Python3 requests库如何仅获取响应头而不下载响应体?适配仅支持GET请求的MinIO服务器
Great question! Since your MinIO server only accepts GET requests and blocks HEAD, you can absolutely replicate the curl -I -X GET behavior in Python's requests library to grab just the headers without downloading the entire file body. Here's how:
The Key Trick: Use stream=True
When you set stream=True in requests.get(), the library won't immediately download the full response body. This lets you access the response headers right away, then close the connection before fetching any of the actual file content.
Here's a working code example:
import requests target_url = "http://domain.dom/path/" # Send GET request with streaming enabled to avoid auto-downloading the body response = requests.get(target_url, stream=True) # Access all response headers (e.g., check Content-Type for file type) print("Response Headers:", response.headers) # Specific header example: print("File Content Type:", response.headers.get("Content-Type")) # Critical: Close the connection to prevent unnecessary data transfer response.close()
Why This Works
stream=Truetells requests to hold off on downloading the response body until you explicitly ask for it.- You can access
response.headersimmediately after the connection is established, just like with a HEAD request—but this uses a GET method that your server allows. - Closing the connection with
response.close()ensures you don't download any of the file content, keeping the request lightweight.
This is exactly equivalent to running curl -I -X GET http://domain.dom/path/—it sends a GET request, retrieves the headers, and stops before fetching the body.
To directly answer your first question: Yes, this method lets you get only the response headers without fetching the body, even when HEAD requests are blocked by the server.
内容的提问来源于stack exchange,提问作者Ouss

