首页 > 解决方案 > 以 PHP 响应作为变量的 JSON REST 请求

问题描述

我正在尝试在标头上获取以下请求 Accept: application/json Content-Type: application/json

{
  "userVO": {
     "userId": "899",
    "lstAuthToken":" uYCpPz6LTYVAZBee8S2cy5ZwFk%3D"
    }
}

发送到以下 URL:http: //54.84.41.76/wkconnects/rest/manageLST/validateLSTAuthToken进行验证。我会得到以下回复:

{
  "ccVerified": "true",
  "sessionAuthenticationToken": "KAA93bndyYaVPCVa8Sx%2FqLomPUP0CSBVHLRBQKMy3e9N%2FnYBEdjXHoN0lmxLfRwljH3PpkeOLIYS%0AQ4WVhF14015bz22HOAq%2B%2FBzMfzI3Z3jFmcuPDhZ6UGGv691Q1azHuQq8U7Biz8DSkPZV0qznohjD%0A43AhVR03LLFcffHI3do%3D",
  "status": "true"
}

我需要将响应 ccVerified 和 sessionAuthenticationToken 作为变量,所以我可以说 =true 或 =false 等。

我尝试使用以下内容但收效甚微:

<?php
$client = new GuzzleHttp\Client();
$res = $client->get('http://54.84.41.76/wkconnects/rest/manageLST/generateLSTAuthToken', [
    'auth' =>  ['899', 'uYCpPz6LTYVAZBeH9Xfi%2F2cy5ZwFk%3D']
]);
echo $res->getStatusCode();           // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();                 // {"type":"User"...'
var_export($res->json());     
?>

标签: phpjsonrest

解决方案


抱歉,我主要用 curl 做这样的事情

<?php                                                                    
    $data_string = json_encode(["userVO" => ['userId' => 899, 'lstAuthToken' => 'token']]);                                                                                                                           
    $ch = curl_init('http://54.84.41.76/wkconnects/rest/manageLST/generateLSTAuthToken');                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($data_string)]);                                                                                                                   
    $result = json_decode(curl_exec($ch));
    if($result->status == "true"){
        $lstAuthToken = $result->lstAuthToken;
        $sessionAuthenticationToken = $result->sessionAuthenticationToken;
    }
    else{
        echo "something went wrong";
    }

    ?>

推荐阅读