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

Python POST请求设置Content-Length遇报错及超时问题求助

Fixing Content-Length Issues with Python requests POST Requests

Let's break down your problems and fix them step by step:

First Issue: InvalidHeader Error for Content-Length

The first error pops up because the requests library requires all header values to be strings or bytes, not integers. When you set "Content-Length": 67, you're passing an int which violates this rule. The quick fix is to convert the value to a string:

"Content-Length": "67"  # Wrap the number in quotes to make it a string

Second Issue: Timeout After Fixing the Header

The timeout is almost certainly caused by a mismatch between the Content-Length you set and the actual size of the data you're sending. Servers use this header to know exactly how much data to expect—if you tell it to wait for 67 bytes but send more or less, it’ll hang waiting for the missing data, leading to a timeout.

Here’s how to fix this properly:

Step 1: Calculate the Exact Content-Length

Instead of guessing 67, compute the actual byte length of your payload after encoding it (since the server receives bytes, not your raw dictionary).

If you’re sending form-encoded data (requests’ default for dict inputs):

import requests
from urllib.parse import urlencode

url_enter = 'some url..'
data_login = {"username": "example", "password": "test123"}  # Your actual login data

# Encode the data to form-urlencoded bytes (the format the server receives)
encoded_data = urlencode(data_login).encode('utf-8')
# Get the exact byte length as a string
content_length = str(len(encoded_data))

headers = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Language": "en-US;q=0.8,en;q=0.7",
    "User-Agent": "some user agent",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": content_length,
    "Content-Type": "application/x-www-form-urlencoded"  # Add this to clarify the data type for the server
}

# Pass the encoded data directly to ensure the length matches what you set
res = requests.post(url_enter, headers=headers, cookies=data_login, data=encoded_data, timeout=7)
print(res.headers)

If you’re sending JSON data:

If your endpoint expects JSON instead of form data, adjust the encoding process:

import json

# Encode data to JSON-formatted bytes
encoded_data = json.dumps(data_login).encode('utf-8')
content_length = str(len(encoded_data))

# Update the Content-Type header for JSON
headers["Content-Type"] = "application/json"
headers["Content-Length"] = content_length

# Use the encoded JSON data in your request
res = requests.post(url_enter, headers=headers, cookies=data_login, data=encoded_data, timeout=7)

Key Takeaways:

  • Avoid hardcoding Content-Length unless you’re 100% certain of the exact byte size of your payload. Calculating it dynamically eliminates mismatches that cause timeouts.
  • If you don’t strictly need to set this header manually, let requests handle it—it automatically computes and adds the correct Content-Length for your data. But since you said you must set it, the above method guarantees accuracy.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 11:07:49