【问题标题】:How to fake guzzele post request to get response data in laravel如何伪造 guzzle post 请求以在 laravel 中获取响应数据
【发布时间】:2018-06-25 13:44:14
【问题描述】:

在 laravel 中我需要伪造 guzzlehttp 发布请求。

        try {
            return $client->request('POST', $url);
        } catch (GuzzleException $e) {
            return $e->getCode();
        }

此请求返回 401 或带有一些数据的成功消息。

目前我需要伪造它来调用其他方法。我怎样才能做到这一点?

这是我的作曲家文件的一部分

"laravel/framework": "5.1.*",
"guzzlehttp/guzzle": "~6.0.0",

【问题讨论】:

  • 在哪里伪造?在测试方法中?
  • @HCK :在控制器中没有。这样做的目的是从该 URL 获得响应。 URL 尚未定义。这就是为什么我需要伪造它
  • 哦,好的,请查看@gordon 的回答。

标签: php laravel guzzle


【解决方案1】:

引用Guzzle docs:

Guzzle 提供了一个模拟处理程序,可用于通过将返回值移出队列来满足 HTTP 请求的响应或异常。

// Create a mock and queue two responses.
$mock = new MockHandler([
    new Response(200, ['X-Foo' => 'Bar']),
    new Response(202, ['Content-Length' => 0]),
    new RequestException("Error Communicating with Server", new Request('GET', 'test'))
]);

$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);

// The first request is intercepted with the first response.
echo $client->request('GET', '/')->getStatusCode();
//> 200
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode();
//> 202

还有:

Guzzle 附带一个 node.js 测试服务器,它接收请求并从队列返回响应。测试服务器公开了一个简单的 API,用于将响应排入队列并检查它收到的请求。

如果 MockHandler 和测试网络服务器不够用,请考虑编写自己的 Handler。详情请见http://docs.guzzlephp.org/en/stable/handlers-and-middleware.html#handlers

【讨论】:

  • 这适用于 GET 请求。你能建议 POST 请求吗?顺便说一句。
  • @Deemantha afaik http 方法无关紧要。模拟处理程序将接受任何东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多