Python发送POST请求到指定API接口

学习笔记作者:admin日期:2025-09-03点击:36

摘要:本文介绍了如何使用Python的requests库模拟浏览器发起POST请求,访问指定的API接口。重点在于构造正确的请求头和请求体,并处理可能遇到的问题如编码格式、Cookie设置等。

1. 问题描述

      用户希望将JavaScript中的fetch请求转换为Python代码,实现相同的HTTP POST请求。

2. 解决方案

      使用Python的requests库可以实现与fetch相同的功能。以下是完整的代码示例:

import requests

url = "https://api.jdjygold.com/gw/generic/jimu/h5/m/homeFeedFlow"

headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,be;q=0.7,ja;q=0.6",
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Google Chrome\";v=\"139\", \"Chromium\";v=\"139\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "cookie": "p",
    "referer": "https://m.jdjygold.com/"
}

data = {
    "reqData": '{"lastId":"","tagId":"20225","invokeSource":"lego"}'
}

response = requests.post(url, headers=headers, data=data)

print("Status Code:", response.status_code)
print("Response Body:", response.text)

3. 关键点说明

  • 请求头(headers):确保所有必要的HTTP头字段都正确设置,包括Accept、Content-Type、Cookie等。
  • 请求体(data):使用字典形式传递数据,requests会自动将其编码为application/x-www-form-urlencoded格式。
  • Cookie:注意当前Cookie值为p,可能是占位符,需替换为实际的Cookie值。
  • Referer:确保Referer字段拼写正确,应为referer而不是Referer

4. 可选方式:手动编码请求体

      虽然不推荐,但也可以手动构造已编码的body字符串,如下所示:

body = "reqData=%7B%22lastId%22%3A%22%22%2C%22tagId%22%3A%2220225%22%2C%22invokeSource%22%3A%22lego%22%7D"

response = requests.post(url, headers=headers, data=body)

5. 处理响应内容

      如果需要解析JSON格式的响应内容,可以添加以下代码:

try:
    print(response.json())
except:
    print("响应不是 JSON 格式")

6. 注意事项

  • 确保content-type中没有多余的分号,如application/x-www-form-urlencoded;charset=UTF-8;应改为application/x-www-form-urlencoded;charset=UTF-8
  • 如果请求失败,检查status_code以确定具体原因。
  • 如果需要长期保持会话或使用代理,可以扩展requests的功能。

上一篇      下一篇