GuzzleHttp - 获取JSON编码的正文

时间:2017-03-07 11:42:46

标签: json api laravel-5.3 guzzlehttp

我为公司创建了一个API客户端,以便从我们的经销商处获取订单。我需要通过PUT确认下载订单。 PUT工作正常但我在确认确认时收到错误。 使用Postman,我收到了JSON正文消息。

当我回复确认时,我收到以下错误:

    Type error: Argument 1 passed to GuzzleHttp\Client::send() must 
    implement interface Psr\Http\Message\RequestInterface, instance of 
    GuzzleHttp\Psr7\Response given, called in 
    /var/www/orders/app/Http/Controllers/edi/OrderController.php on line 86

这是第86行:

    $response = $client->send($apirequest);

相关代码:

    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use GuzzleHttp\Exception\GuzzleException;
    use GuzzleHttp\Client as GuzzleHttpClient;
    use GuzzleHttp\Psr7\Stream;
    use Illuminate\Support\Facades\Input;
    use Response;
    use XmlParser;
    use Psr\Http\Message\RequestInterface;

    public function orderConfirm()
    {
    $uri = config('services.orders.orderack');

    $formdata = Input::all();
    $orders = Input::get('orders');

    try {
        $client = new GuzzleHttpClient([
            'headers'=> [
                'Authorization' => '$user',
                'ContractID' => '$contract',
                'Content-Type' => 'application/json']
            ]);

        $apirequest = $client->request('PUT', $uri,
            ['body' => json_encode(
                [
                    $orders
                ]
            )]
        );

        $response = $client->send($apirequest);
        $contents = (string) $response->getBody();

        return $contents;

    }
    catch (RequestException $ex) {
        //Exception Handling
        echo $ex;
    }

Postman的输出是:

    "Number of Orders Acknowledged: 1"

来自SO的其他帖子,这个:

     $contents = (string) $response->getBody();

是让身体和其他人解决问题的方法,但这对我不起作用。

显然我在这里仍然遗漏了一些东西!

1 个答案:

答案 0 :(得分:0)

调用$client->request()实际上是在执行请求(这就是为什么它返回GuzzleHttp\Psr7\Response的实例)而不是构建请求对象以便稍后发送。你不需要告诉客户发送任何东西,因为它已经被发送了;您只需将$response变量设置为$client->request()的调用值。

这可以在他们的PSR7文档中的Body example中看到。

$response = $client->request('GET', 'http://httpbin.org/get');

要手动构建请求对象,您必须使用其构造函数documented under Requests创建GuzzleHttp\Psr7\Request的实例。

// Create a request using a completely custom HTTP method
$request = new \GuzzleHttp\Psr7\Request('MOVE', 'http://httpbin.org/move');

echo $request->getMethod();
// MOVE