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"))

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this and it still returned NULL
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 php.net/manual/fr/function.curl-setopt.php they preconize like this.
I tried it and it did not work
Take a look here, you need to get the real errors to resolve this problem. stackoverflow.com/questions/3987006/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.