【问题标题】:Unable to get response that I sends using GuzzleHttp\Psr7\Response on request made by client无法获得我使用 GuzzleHttp\Psr7\Response 根据客户端发出的请求发送的响应
【发布时间】:2021-06-23 10:08:58
【问题描述】:

我正在使用 GuzzleHttp\Client 从客户端向另一个用作服务器的端口上的页面发送请求

use SL\Controllers\LoginController;
use SL\FileHelper;
use GuzzleHttp\Client;

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . "config/config.php";

$client = new Client();
$response = $client->request('get','http://myip:75/src/LoginVerification.php?username=asd&password=asd');

请求在页面上提供

require_once(__DIR__ . '/../config.php');

use Moodle\Manager\UserManager;
use GuzzleHttp\Psr7\Response;

$userManager = new UserManager();
$user;


$username = $_GET["username"];
$password = $_GET["password"];

$isLogin = $userManager->verifyLogin($username, $password, $user);
if($isLogin)
    $body = "yahoo";
else
    $body = "oooops";

$status = 201;
$headers = ['Content-Type' => 'application/json'];
$protocol = '1.1';
$response = new Response($status, $headers, $body, $protocol);
return $response;

请忽略 GET 中传递的密码,因为我这里主要关注的是发送请求和获取响应。

在服务器上提供请求后,我做出的响应如下

phrases:array(58)
reasonPhrase:"Created"
statusCode:201
headers:array(1)
headerNames:array(1)
protocol:"1.1.1"
stream:GuzzleHttp\Psr7\Stream
stream:resource id='10' type='stream'
size:null
seekable:true
readable:true
writable:true
uri:"php://temp"

但是收到的是这个

headerNames:array(9)
headers:array(9)
statusCode:200
reasonPhrase:"OK"
phrases:array(58)
protocol:"1.1"
headerNames:array(9)
headers:array(9)
phrases:array(58)
reasonPhrase:"OK"
statusCode:200
stream:resource id='4' type='stream'
size:null
seekable:true
readable:true
writable:true
uri:"php://temp"

这与我创建的响应不同。

【问题讨论】:

  • 您正在努力解决的两者之间有什么区别?您尝试过哪些检查为什么存在差异?
  • Nico,我提到的第一个响应是我创建的响应,当我在 body [$response->getBody()->getcontents( )] 以验证是否已保存数据作为响应。但是第二个响应独立于我在服务器端所做的事情,如果我没有在服务器上创建响应,那么将返回相同的响应
  • return $response 看起来不像您真的在发送响应
  • 我也试过了,但在这种情况下,用户只发送状态..但我也想发送正文中的数据

标签: php request response guzzle


【解决方案1】:

由于我没有使用 Laravel,所以这个没有得到我想要的响应的问题可以通过创建一个简单的 stdClass 对象来解决,并通过执行 json_encode 来回显这个对象,然后你可以在响应正文中获取数据。

$response = new stdClass();
$isLogin = $userManager->verifyLogin($username, $password, $user);
    if($isLogin)
        $response->body = "yahoo";
    else
        $response->body = "oooops";
    
    $response->status = 201;
    $response->headers = ['Content-Type' => 'application/json'];
    $response->protocol = '1.1';
    echo json_encode($response);

要在客户端获取它,您只需这样做

$data = $response->getBody()->gtContents();

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2015-11-29
    • 2020-12-09
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多