You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Python Requests库请求头能否使用二维字典及指定请求头格式转换的技术求助

Can You Use a 2D Dictionary as Headers in 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 Authorization key in your headers dictionary.
  • For application/x-www-form-urlencoded content type, make sure you’re sending your data using the data parameter (not json) in your Requests call, as shown in the example.

内容的提问来源于stack exchange,提问作者Winux503

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 09:57:34