Python请求POST缺少特定URL的Content-Length。

问题描述 投票:0回答:1

我试图使用 Requests 模块做一个基本的 POST 请求,但是 Content-Length 总是缺失,所以服务器忽略了有效载荷。我的payload是一个dict,但Request似乎无法计算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(如上所述)和干脆让Request来计算,但从来没有发生过这种情况,它就是 始终 在发送的头文件中不见了。

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

有人知道如何解决这个问题吗?

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

python post python-requests content-type content-length
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.