I need to make a POST request using a JSON object as the body. Both of these methods are giving me HTTP 500 server errors. Is there anything glaringly wrong with my code? Be gentle... I've tried several methods including
$checkfor = ("'serverId':'Server','featureId':'Feature','propertyId':'Property'");
$checkforJson = json_encode($checkfor);
$uri = "http://localhost:8080/v1/properties";
$response = \Httpful\Request::post($uri)
->method(Request::post)
->withoutStrictSsl()
->expectsJson()
->body($checkforJson)
->send();
pre($response);
Which uses the HTTPful resource. And I have tried using cURL
$service_url = "http://localhost:8080/v1/properties";
// Initialize the cURL
$ch = curl_init($service_url);
// Set service authentication
// Composing the HTTP headers
$body = array();
$body[] = '"serverId" : "Server"';
$body[] = '"featureId" : "Feature"';
$body[] = '"propertyId" : "Property"';
$body = json_encode($body);
$headers = array();
$headers[] = 'Accept: application/xml';
$headers[] = 'Content-Type: application/xml; charset=UTF-8';
// Set the cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
// Execute the cURL
$data = curl_exec($ch);
// Print the result
pre($data);
I had similar issues a while back.
A solution that worked for me was this:
$url = 'http://yourURL.com/api';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data),
)
);
$context = stream_context_create($options);
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
Similar answers can be found HERE
Your json_encode requires an array.
It should look like this
<?php
$checkfor = ([
'serverId'=>'Server',
'featureId'=>'Feature',
'propertyId'=>'Property'
]);
$checkforJson = json_encode($checkfor);
var_dump($checkforJson); // this will now work
https://3v4l.org/RG5Zv
For better understanding read doc
UPDATE I also notice on the curl script, your array needs fixed again
$body['serverId'] = 'Server';
and dont json encode the post fields afterwards, it takes an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With