I am sending a POST request to a URL. It works correctly in python but in php-curl, I always get a bad request error (i.e. my POST data is not as expected by the server)
Python code: (works correctly. 200 OK)
import httplib, urllib, json
def SendRequest(param1):
url = "api.xyz.com"
body = {"version": "1.0", "data":[{"param1":param1, "age":35}]}
jsonBody = json.dumps(body)
headers = {"Content-type": "application/json",
"Accept": "application/json; charset=utf8"}
conn = httplib.HTTPConnection(url)
conn.request("POST", "/api/?client_id=xx-xx-xx", jsonBody, headers)
response = conn.getresponse()
php-cURL code (does not work. 406 Bad request error)
function sendCurlRequest($param1)
{
$payload = preparePayload($param1);
$url = "http://api.xyz.com/api/?client_id=xx-xx-xx";
$jsonResponse = executePOSTRequest($url, $payload);
$response = json_decode($jsonResponse);
}
function preparePayload($param1)
{
$payload = array("version" = "1.0",
"data" => array(array("param1" => $param1,
"age" => 35
)
),
);
$jsonPayload = json_encode($payload);
return $jsonPayload;
}
function executePOSTRequest($url, $payload)
{
$newlines = array("\r", "\n", " ");
$url = str_replace($newlines, '', $url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADERS,array('Content-Type:application/json; Accept: application/json; charset=utf8'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
}
I know there is some mistake in my use of cURL. Please suggest.
Update: Use of double array in php is because server expects the JSON string (POST payload) in this format
{
"version": "1.0",
"data":
[{"param1":name, "age":35},{"param1":name,"age":60}]
}
In python, I am using list of dict; in php I think it is array of arrays only.