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

时间:2020-06-02 15:13:15

标签: python post python-requests content-type content-length

我正在尝试使用Requests模块执行基本的POST请求,但是Content-Length始终丢失,因此服务器将忽略有效负载。我的有效负载是字典,但是请求似乎无法计算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标头-这是否意味着这是编码问题?

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

edit:我还注意到,这仅在特定的URL上发生,任何其他URL似乎都很好(content-length和type都可以)。我只能假设这是请求模块的问题,因为它与发送的数据有关。也许请求模块会先检查网址,然后对不同的网址采取不同的处理方式?

1 个答案:

答案 0 :(得分:0)

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