简体   繁体   中英

POST request payload in python not reaching PHP server

I am trying to send a JSON payload with session request in python to a PHP server. The session itself is established and cookies are accepted by the server but when I print out the $_POST , it returns an empty array. It looks like the payload is not being sent with the request or maybe PHP doesn't recognize it.

Client Side - Python:

import json
import requests

url = 'https://prov.is.st.com/eventpost.php'
    payload = {
        'script': 'pyt.sh',
        'status': 'Success'
    }

    s = requests.Session()
    s.cookies.set('provisioning', cookie, domain='prov.is.st.com')
    headers = {
    'Content-Type': 'application/json'
    }
    s.headers.update(headers)
    response = s.post(url, data=payload, verify=False)
    print(response.text)

Server Side - PHP:

<?php
print_r($_POST);
if(isset($_POST['status'])){
 $status = $_POST['status'];
}
else{
  $status=0;
}

if (isset($_POST['script'])) {
  $script=$_POST['script'];
} else {
  $script="unknown";
}

if (isset($_COOKIE['provisioning'])) {
  $cookie=$_COOKIE['provisioning'];
   print "OK: Message accepted: [$status][$script]\n";
  }
 else {
  print "ERROR: NO cookie provided.\n";
}

Output

Array
(
)
OK: Message accepted: [0][unknown]

As per the documentation here: https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests , in order to post JSON data, you should use either of the following ways:

import json
...
response = s.post(url, data = json.dumps(payload), verify = False)

or

...
response = s.post(url, json = payload, verify = False)

Note, the json parameter is ignored if either data or files is passed.

Using the json parameter in the request will change the Content-Type in the header to application/json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM