简体   繁体   中英

curl php json always return a wrong response

I need your help to check whats wrong with my code. I had tried to post a json data from postman and it returnen a correct response. But the following code always returns a wrong response.

<?php
$data_login = array('email'=>'dada@dada.com','password'=>'hahaha','confirmation_password'=>'hahaha');

$api_data = json_encode($data_login);
$api_url = 'http://dev.badr.co.id/freedom/auth/register';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

curl_close($ch);

echo $result;

wrong response :

{"success":false,"message":"1000: Not a valid request"}

correct response :

{
    "success": true,
    "message": "user registration success",
    "data": null
}

This return a correct response if i post the data using postman :

correct_response

If curl_exec() is returning false that means that the request is failing somehow.

You can work out how by using the curl_error() function . Call it in between curl_exec() and curl_close() and it will return a string with information on what went wrong with the request.

Check the return values of the initializing and executing cURL functions. curl_error() and curl_errno() will contain further information in case of failure:

try {
    $data_login = array('email'=>'dada@dada.com','password'=>'hahaha','confirmation_password'=>'hahaha');
    $api_data = json_encode($data_login);
    $api_url = 'http://dev.badr.co.id/freedom/auth/register';

    $ch = curl_init();

    if (FALSE === $ch)
        throw new Exception('failed to initialize');

    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $api_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    if (FALSE === $result)
        throw new Exception(curl_error($ch), curl_errno($ch));
} catch(Exception $e) {

    echo sprintf(
        'Curl failed with error #%d: %s',
        $e->getCode(), $e->getMessage());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM