gpt4 book ai didi

Python 使用 content-type=x-www-form-urlencoded 请求 POST json 数据

转载 作者:可可西里 更新时间:2023-11-01 16:36:21 26 4
gpt4 key购买 nike

请求:

# coding=utf-8
from __future__ import print_function

import requests

headers = {
# 'content-type': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
}

params = {
'a': 1,
'b': [2, 3, 4],
}

url = "http://localhost:9393/server.php"
resp = requests.post(url, data=params, headers=headers)

print(resp.content)

php 接收:

// get HTTP Body
$entityBody = file_get_contents('php://input');
// $entityBody is: "a=1&b=2&b=3&b=4"

// get POST
$post = $_POST;
// $post = ['a' => 1, 'b' => 4]
// $post missing array item: 2, 3

因为我还使用 jQuery Ajax POST,默认内容类型 = application/x-www-form-urlencoded。而 PHP 默认 $_POST 只存储值:

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

http://php.net/manual/en/reserved.variables.post.php

所以,我也想像 jQuery 默认行为一样使用 Python 请求,我该怎么办?

最佳答案

PHP 将只接受带有方括号的变量的多个值,表示一个数组(参见 this FAQ entry )。

所以你需要让你的 python 脚本发送 a=1&b[]=2&b[]=3&b[]=4 然后在 PHP 端发送 $_POST看起来像这样:

[ 'a' => 1, 'b' => [ 2, 3, 4] ] 

关于Python 使用 content-type=x-www-form-urlencoded 请求 POST json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com