During a university project, I’ve built a ReST API with Spring Boot. I’m currently trying to write a client to use my ReST API.
I have this URI to get a "Bearer" token:
When I create an HTTP request within IntelliJ they are working fine, like this:
POST http://localhost:8080/api/newQrCode
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX0FETUlOIl0sImV4cCI6MTYxNDYwMTE4Nn0.rPVs-ZYDKiHB1tvWGy0LWTkI8drzsNenLecIVy0-dHs
Content-Type: application/json
{"texteCode" : "Je suis un autre Qr Code", "scoreCode": "1"}
and the result is:
POST http://localhost:8080/api/newQrCode
HTTP/1.1 200
Set-Cookie: JSESSIONID=35D91AE8B080F7E719BBBBC9DB642614; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: text/plain;charset=UTF-8
Content-Length: 14
Date: Sun, 21 Feb 2021 22:08:57 GMT
Keep-Alive: timeout=60
Connection: keep-alive
Qr Code créé
Response code: 200; Time: 146ms; Content length: 12 bytes
The problem I’m facing is that I have to do a PHP rest client, and I can’t do the post request (getting the token works well):
function test($token){
$url = "http://localhost:8080/api/newQrCode"; // modifier le produit 1
$data = "{"texteCode" : "Je suis un autreuhhuhu Qr Code", "scoreCode": "1"}n";
$data = json_encode(array("texteCode: Je suis un autreuhhuhu Qr Code", "scoreCode : 1"));
$data = json_encode(array("texteCode" => "Je suis un autreuhhuhu Qr Code", "scoreCode" => 1));
$data = json_encode("{"texteCode" : "Je suis un autreuhhuhu Qr Code", "scoreCode": "1"}n");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: " . $token, "Content-Type: application/json"));
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
var_dump(json_decode($response));
if (!$response)
{
return false;
}
return true;
}
During my web research, I had read different ways to pass JSON data, but I didn’t manage to find the right one.
There is this message in the Spring console :
Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing:
org.springframework.http.ResponseEntity<java.lang.String>
com.dill.api_rest.controleur.ApiRestControleur.createQrCode(com.dill.api_rest.modele.QrCode)]
Just for the test, I’ve done a version of this POST request with HttpClient in Java and it’s also working very well.
So my question is: Is my problematic feasible with PHP and curl and am I doing it wrong, or should O go with another tool / another tech to do that (like java)?
2
Answers
After more investigations there was a extra empty character in my token string. I removed it and it's working well now.
Try to fix php code a bit:
data
header (
Bearer
is missing?)