Жрать |Асинхронные запросы |Ошибка неверного типа ресурса - PullRequest
0 голосов
/ 18 апреля 2019

Я пытаюсь связать http-запросы, где второй запрос зависит от ответа первого.Я наткнулся на Guzzle Client-> sendAsync ().

Ошибка, которую я получаю:

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

Вот что у меня есть до сих пор:

$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();

Есть мысли о том, что я делаю неправильно?

Ответы [ 2 ]

2 голосов
/ 20 апреля 2019

Вы должны вручную закодировать ваш PHP-массив в JSON, чтобы использовать его с 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();
1 голос
/ 20 апреля 2019

Если вы хотите передать параметры с помощью "json", вам нужно изменить ваш код, как показано ниже:

$secondRequest = new Psr7\Request('POST', 'api/anotherapi', $searchHeaders);
     $secondResponse = $client->sendAsync($searchRequest, [
         'json' => [
         'field1' => 'val1',
         'field2' => 'val2',
         'field3' => json_encode($firstResponse),
         'field4' => 'val3'
        ])->function($response2) use ($client) {
          return $response2->getBody()->getContents();
     });

См. Документацию здесь (http://docs.guzzlephp.org/en/stable/quickstart.html):

An easy way to upload JSON data and set the appropriate header is using the json request option:

$r = $client->request('PUT', 'http://httpbin.org/put', [
    'json' => ['foo' => 'bar']
]);

Проверьте ответ Алексея Шокова для более подробной информации.

...