关于Python Requests库请求头能否使用二维字典及指定请求头格式转换的技术求助
Hey there! Let's break this down clearly for you.
First off, the straight answer: no, you can’t use a nested (2D) dictionary for request headers in Python Requests. The library expects headers to be a flat, single-level dictionary where every key and value is a string. That’s exactly why you ran into that error—when you tried using a nested structure, Requests saw the second layer as a dictionary instead of the string it requires.
Fixing Your Specific Header Format
Luckily, converting your required headers into a Requests-compatible format is straightforward. You just need to represent each header field as a key-value pair in a single-level dictionary, with the full header value as a string (even for the OAuth authorization line).
Here’s the exact code you can use (don’t forget to replace the placeholder values with your actual credentials):
import requests # Build your headers as a flat dictionary headers = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": 'OAuth oauth_consumer_key="your_consumer_key", oauth_nonce="random_string_or_timestamp", oauth_signature="your_consumer_secret&", oauth_signature_method="PLAINTEXT", oauth_timestamp="current_timestamp", oauth_callback="your_callback"', "User-Agent": "some_user_agent" } # Example POST request using these headers # Replace with your actual endpoint and form data response = requests.post("https://your-target-api.com", headers=headers, data={"key": "value"})
Why Your Nested Approach Failed
If you tried something like this (a nested dictionary for Authorization), that’s what caused the error:
# ❌ THIS WILL FAIL bad_headers = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": { "oauth_consumer_key": "your_consumer_key", "oauth_nonce": "random_string_or_timestamp" # ... other OAuth params }, "User-Agent": "some_user_agent" }
Requests doesn’t parse nested dictionaries for headers—each header value must be a single string that matches exactly what the server expects to receive in the HTTP request.
Quick Pro Tips
- Always double-check that all header values are strings (even numeric values like timestamps should be converted to strings first).
- If you need to dynamically generate the OAuth authorization string, build it step-by-step as a string first, then assign it to the
Authorizationkey in your headers dictionary. - For
application/x-www-form-urlencodedcontent type, make sure you’re sending your data using thedataparameter (notjson) in your Requests call, as shown in the example.
内容的提问来源于stack exchange,提问作者Winux503

