3

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);
1
  • PHP warning, json_encode() expects parameter 2 to be integer from the Apache logs. And the server itself is erroring with status.code unknown (helpful i know) Commented Oct 25, 2018 at 11:29

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry man I'm kind of a n00b at coding, I am getting an output from that of resource #id 3. How do i view the contents of Context?
You can use $result = file_get_contents( $url, false, $context ); $response = json_decode( $result ); after $context and access it via the $response
That appears to have worked Daryn. However i believe there is an issue with the format in which the Json is being parsed. Which is an error being thrown by a Java server so i am going to look more into that. Thank you for your help man
2

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.

12 Comments

Unforunately, this didn't work for me. But i will make sure to keep it in my code, thank you for the tip
you must have more errors then, but this at least gets you the correct array. any new error messages?
Yeah I am now getting the json_decode() expects parameter 1 to be string, resource given in /var/www/etc
Aha! Following your updates i have stopped getting any errors in Apache! I am getting a server error saying "status.cause:com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input" - but i assume that is another question for another thread? Edit: I was decoding in the first example, not the second, apologies.
Yeah i had a hunch that was the case. I did look up code 100 and saw it's nothing bad. I will continue looking into the Java errors.
|
1

Have you tried:

$body = array(
  "serverId" => "Server",
  "featureId" => "Feature",
  "propertyId" => "Property",
);

$body = json_encode($body);

Maybe its the way your array is setup

1 Comment

Unfortunately, neither of these worked. Thank you for the suggestion though
-1

Try this:

public function add($title, $release_date, $genre){
        global $conn;

        $sql = "CALL `addBook` (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $title, $release_date, $genre);
        if($stmt->execute()){
            return true;
        }else{
            return false;
        }
    }

here is how to execute it


$data = json_decode(file_get_contents("php://input"), true);
                if(!isset($data["title"], $data["release_date"], $data["genre"])){
                    echo "Hianyzo adatok";
                    http_response_code(404);
                }

                $success = $konyv->addBook($data["title"], $data["release_date"], $data["genre"]);
                if($success){
                    echo "sikeres hozzáadás";
                }break;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.