Python请求显式设置头导致400响应

2024-04-26 05:59:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试向web服务器发帖。我有数据,我想张贴在正文和标题(采取直接从铬)。在不涉及太多细节的情况下,当我显式地设置头时,我得到一个400响应代码

# Explicitly set headers causes 400 response    
req = requests.post(url, auth_form, headers=authenticate)
print(req.status_code)

但以下返回200响应代码:

# Setting data as my form to post and headers as json
# Returns a 200 response code    
req = requests.post(url, auth_form, authenticate)
print(req.status_code)

我试图通过代码模拟登录。即使我收到200响应,我也没有成功登录。我怀疑这是因为我没有正确设置标题,但我不确定

实际上,我能够完全删除这些头(headers=或json),并且仍然收到一个200响应代码。我相信这加强了标题设置不正确的想法

# Removing headers entirely 
# Returns a 200 response code    
req = requests.post(url, auth_form)
print(req.status_code)

我不确定是否需要额外的细节(比如一些标题是什么)。如果是这样,我将尽可能多地提供这些信息

编辑:标题,按要求:

    authenticate = {}
    authenticate["Accept"] = accept
    authenticate["Accept-Encoding"] = "gzip, deflate, br"
    authenticate["Accept-Language"] = "en-US,en;q=0.8"
    authenticate["Cache-Control"] = "max-age=0"
    authenticate["Connection"] = "keep-alive"
    authenticate["Host"] = dns + ":" + str(port)
    authenticate["Origin"] = "http://" + dns + ":" + str(port)
    authenticate["Referer"] = "http://" + dns + ":" + str(port) + "/eproc/"
    authenticate["Upgrade-Insecure-Requests"] = upgrade_insecure
    authenticate["Cookie"] = "ID=" + self.session_id
    authenticate["User-Agent"] = user_agent

    auth_form = {}
    auth_form["username"] = username
    auth_form["password"] = password

Tags: 代码formauthurl标题responsestatuscode