0

I gave myself a project that involves basic CRUD operations with Spring-boot Java as back-end and PHP as front-end. I have my API up and running, I have tested the routes with Postman and I am getting back a response depending on the header I set in postman like so. Here you can also see in my Java backend code I make sure my API can return both XML and JSON.

@GetMapping(path = "/cabbage",
        produces = {
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE,
        })
public @ResponseBody
Iterable<CabbageFarm> getCabbageData() {
    return cabbageRepo.findAll();
}

The problem now for me is consuming the route with cURL in order to store the JSON or XML values I get in an array for further manipulation but when ever I do, I get NULL. Here is my php code.

<?php

    $ch = curl_init();
    $url = "localhost:8080/cabbage";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"));
    $result = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($result, true);

    var_dump($data);
?>

In this code above I am attempting to consume JSON hence the

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: Accept:application/json"))

Assafs
  • 3,257
  • 4
  • 26
  • 39

1 Answers1

0

Perhaps because you close curl resource too early, try to reverse these lines

curl_close($ch); $data = json_decode($result, true);

like this

$data = json_decode($result, true); curl_close($ch);
Lounis
  • 597
  • 7
  • 15
  • I tried this and it still returned NULL – Ademola Adigun Feb 16 '20 at 14:56
  • hum, the header seems to be malformated, can you change `array("Content-Type: Accept:application/json")` by this `array("Content-Type: application/json")`. If you look at php docs https://www.php.net/manual/fr/function.curl-setopt.php they preconize like this. – Lounis Feb 16 '20 at 15:01
  • I tried it and it did not work – Ademola Adigun Feb 16 '20 at 15:08
  • Take a look here, you need to get the real errors to resolve this problem. https://stackoverflow.com/questions/3987006/how-to-catch-curl-errors-in-php – Lounis Feb 16 '20 at 15:12