vikyd
vikyd

Reputation: 2033

Python request POST json data using content-type=x-www-form-urlencoded

py request:

# 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 recieve:

// 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

Because I also using jQuery Ajax POST which default content-type = application/x-www-form-urlencoded. And PHP default $_POST only stores value :

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

So, I want to also use Python request the same as jQuery default behavior, What can I do?

Upvotes: 3

Views: 7080

Answers (1)

weirdan
weirdan

Reputation: 2632

PHP will only accept multiple values for variables with square brackets, indicating an array (see this FAQ entry).

So you will need to make your python script to send a=1&b[]=2&b[]=3&b[]=4 and then $_POST on PHP side will look like this:

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

Upvotes: 2

Related Questions