首页 > 解决方案 > Python 请求 POST 缺少特定 URL 的 Content-Length

问题描述

我正在尝试使用 Requests 模块执行基本的 POST 请求,但 Content-Length 始终丢失,因此服务器忽略了有效负载。我的有效负载是一个字典,但请求似乎无法计算内容长度。

这是我的代码:

form = {
'InternalApplicationSource' : 'signedinhome.recommendedjobs',
'__RequestVerificationToken' : str(rvt),
'Candidate.CVName' : 'CV.docx',
'JobTitle' : str(jtl),
'AppSource.AppSourceId' : '',
'AppSource.MatchCount' : '',
'IsExternalApplication' : 'False',
'Candidate.CoverLetterPreference' : 'None',
'Candidate.IsExternalApplication' : 'False',
'JobId' : str(jid),
'Source' : 'signedinhome.recommendedjobs',
'UserHasRegisteredThroughJob' : 'False'
}


post_headers = {
'Host': 'www.reed.co.uk',
'Origin' : 'https://www.reed.co.uk',
'User-Agent': browser,
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.7,jv;q=0.3',
'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'TE': 'Trailers'
}

post_headers.update({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Referer' : joburl , 'X-Requested-With': 'XMLHttpRequest', 'Content-Length':str(len(form))})
postres = session.post('https://www.reed.co.uk/api/application/apply',headers=post_headers,data=form)

这些是实际发送的标头(从 postres.request.headers 获得)

User-Agent : Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0
Accept-Encoding : gzip, deflate, br
Accept : */*
Connection : keep-alive
Host : www.reed.co.uk
Origin : https://www.reed.co.uk
Accept-Language : en-US,en;q=0.7,jv;q=0.3
DNT : 1
TE : Trailers
Referer : https://www.reed.co.uk/jobs/
X-Requested-With : XMLHttpRequest

我已经尝试过设置 Content-Length (如上所述)并简单地让 Requests 来计算它,但这从未发生过,它总是从发送的标头中丢失。

我注意到它还省略了 Content-Type 标头 - 这是否意味着这是一个编码问题?

有谁知道如何解决这一问题?

编辑:我还注意到这只发生在这个特定的 URL 上,任何其他 URL 似乎都很好(内容长度和类型都可以)。我只能假设这是请求模块的问题,因为它涉及发送的数据。也许请求模块首先检查 URL 并以某种方式对不同的 URL 采取不同的行为?

标签: pythonpostpython-requestscontent-typecontent-length

解决方案


原来我的请求被重定向了,所以我在屏幕上打印的只是最后一个请求......当我使用 时allow_redirects=False,我终于可以看到我原来的 POST 请求。而且我可以看到实际上 Content-Type 和 Content-Length 都在那里,都是正确的!


推荐阅读