Reputation: 33
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);
Upvotes: 3
Views: 19490
Reputation: 71
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
Upvotes: 7
Reputation: 12384
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
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.
Upvotes: 2
Reputation: 582
Have you tried:
$body = array(
"serverId" => "Server",
"featureId" => "Feature",
"propertyId" => "Property",
);
$body = json_encode($body);
Maybe its the way your array is setup
Upvotes: 1