PHP curl和输出api响应

时间:2018-09-21 12:00:39

标签: php rest curl

我正在使用cURL与API进行接口。完成API所需的操作后,我想做的就是输出API响应。

    <?php

/*
* Server REST - user.login
*/

$input = file_get_contents("php://input");
$xml_input = simplexml_load_string($input);
$xml_arr = json_decode(json_encode($xml_input, TRUE));
// REST Server URL
$request_url = 'http://xxx.localhost:8888/api/v1/user/login.json';

// User data
$user_data = array(
    'username' => $xml_arr->Username,
    'password' => $xml_arr->Password,
);

// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_code == 200) {
    $logged_user = json_decode($response);
}
else {
    $http_message = curl_error($curl);
    return http_response_code(401);
}

$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;
if($xml_arr->Action == "Delete"){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://xxx.localhost:8888/api/v1/logic_melon/' . $xml_arr->JobReference);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
} elseif($xml_arr->Action == "Add") {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,'http://xxx.localhost:8888/api/v1/logic_melon');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'X-CSRF-Token: ' . $logged_user->token, 'Cookie: ' . $cookie_session));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($xml_arr));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
}

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($http_code == 200)
{
    // Convert json response as array
    $response = json_decode($response);
    echo $response;
}
else
{
    // Get error msg
    $http_message = curl_error($curl);
}

api返回响应代码和消息,我该如何将其输出给用户?返回$ response似乎无法完成任务。

0 个答案:

没有答案