枪口|异步请求|无效的资源类型错误 [英] Guzzle | Async requests | Invalid resource type error

查看:100
本文介绍了枪口|异步请求|无效的资源类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试链接http请求,其中第二个请求取决于第一个请求的响应.我遇到了Guzzle Client-> sendAsync().

I am trying to chain http requests, where the second request is dependent on the response from the first. I came across Guzzle Client->sendAsync().

我得到的错误:

exception: "InvalidArgumentException"
file: "...\guzzlehttp\psr7\src\functions.php"
line: 116
message: "Invalid resource type: array"

这是我到目前为止所拥有的:

Here's what I have so far:

$client = new Client([...]);
$headers = [...];
$req = new Psr7\Request('GET', '/api/someapi', $headers);
$finalResponse = $client->sendAsync($req)->then(function($response1) use ($client) {
    $firstResponse = json_decode($response1->getBody()->getContents());
    // $firstResponse is an array
    $secondHeaders = [...];
    $secondRequest = new Psr7\Request('POST', 'api/anotherapi', $searchHeaders, [
         'json' => [
         'field1' => 'val1',
         'field2' => 'val2',
         'field3' => json_encode($firstResponse),
         'field4' => 'val3'
        ]
     ]);
     $secondResponse = $client->sendAsync($searchRequest)->function($response2) use ($client) {
          return $response2->getBody()->getContents();
     });
     return $secondResponse->wait();
});
return $finalResponse->wait();

对我在做什么错有任何想法吗?

Any thoughts about what I'm doing wrong ?

推荐答案

您必须手动将PHP数组编码为JSON才能与Psr7\Request

You have to encode your PHP array to JSON manually to use with Psr7\Request

$secondRequest = new Psr7\Request('POST', 'api/anotherapi', $searchHeaders, json_encode([
    'field1' => 'val1',
    'field2' => 'val2',
    'field3' => json_encode($firstResponse),
    'field4' => 'val3'
]));

或者使用->postAsync()代替->sendAsync(),更容易

$client = new Client();
$headers = [];
$finalResponse = $client->getAsync('/api/someapi', ['headers' => $headers])
    ->then(function ($response1) use ($client) {
        $firstResponse = json_decode($response1->getBody()->getContents());
        // $firstResponse is an array
        $secondHeaders = [];
        $secondResponse = $client->postAsync('api/anotherapi', [
            'headers' => $secondHeaders,
            'json' => [
                'field1' => 'val1',
                'field2' => 'val2',
                'field3' => json_encode($firstResponse),
                'field4' => 'val3'
            ],
        ])->then(function ($response2) use ($client) {
            return $response2->getBody()->getContents();
        });

        // You don't need to call ->wait() here, Guzzle will resolve the promise for you
        return $secondResponse;
    });

return $finalResponse->wait();

这篇关于枪口|异步请求|无效的资源类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆