带有表单数据的POST请求 [英] POST request with form data

查看:381
本文介绍了带有表单数据的POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟一个请求 具有各种标题和括号内的表单数据.

I'm trying to simulate a request that has various headers and bracketed form data.

表格数据:

{"username": "MY_USERNAME", "pass": "MY_PASS", "AUTO": "true"}

这是Chrome控制台中显示的表单数据 因此,我尝试将其与Python的requests库放在一起:

That is the form data shown in the console of Chrome So I tried putting it together with Python's requests library:

import requests
reqUrl = 'http://website.com/login'
postHeaders = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip,deflate',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Length': '68',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Host': 'website.com',
    'Origin': 'http://www.website.com',
    'Referer': 'http://www.website.com/',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36'
}

payload = {"username": "MY_USERNAME",
    "pass": "MY_PASS",
    "AUTO": "true"
}

session = requests.Session()
response = session.post(reqUrl, data=payload, headers=postHeaders)

我收到答复,但显示:

{"status":"failure","error":"Invalid request data"}

我会错误地实施表单数据吗?我还认为这可能与修改Content-Length有关?

Am I going about implementing the form data wrong? I was also thinking it could have to do with modifying the Content-Length?

推荐答案

是的,您正在设置内容长度,覆盖了requests可能设置的任何内容.您设置的标题过多,请将其中的大部分留给库:

Yes, you are setting a content length, overriding anything requests might set. You are setting too many headers, leave most of those to the library instead:

postHeaders = {
    'Accept-Language': 'en-US,en;q=0.8',
    'Origin': 'http://www.website.com',
    'Referer': 'http://www.website.com/',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36'
}

足够了.所有其他都将为您生成.

is plenty. All the others will be generated for you.

但是,从您对表单数据的描述来看,您似乎正在发布JSON.在这种情况下,请使用json关键字参数而不是data,这会将您的有效负载编码为JSON并将Content-Type标头设置为application/json:

However, from your description of the form data, it looks like you are posting JSON instead. In that case, use the json keyword argument instead of data, which will encode your payload to JSON and set the Content-Type header to application/json:

response = session.post(reqUrl, json=payload, headers=postHeaders)

这篇关于带有表单数据的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆