PHP:Guzzle客户端-到其他服务器的代理请求

时间:2018-11-14 10:02:36

标签: php laravel guzzle

因此,我只是尝试将所有请求代理到另一台服务器。

除了要更改基本uri外,我希望所有内容都相同。

<?php

namespace App\MicroServices\Example\Clients;

use GuzzleHttp\Client;
use Illuminate\Http\Request;

/**
 * Class ExampleClient
 * @package App\MicroServices\Example\Clients
 */
class ExampleClient extends Client implements ClientInterface
{

/**
 * ExampleClient constructor.
 */
public function __construct()
{
    parent::__construct([
        'base_uri' => config('example.base.uri'),
        'timeout' => config('example.client.timeout'),
    ]);
}

/**
 * @param Request $request
 *
 * @return string
 *
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
public function proxyToExampleServer(Request $request)
{
    $method = $request->getMethod();
    $body = json_decode($request->getContent(), true);
    $path = $request->path() . ($request->getQueryString() ? ('?' . $request->getQueryString()) : '');
    $headers = [];

    foreach ($request->header() as $key => $value)
    {
        $headers[$key] = $value[0];
    }

    $headers['Authorization'] = $request->bearerToken();

    return $this->request($method, $path, ['headers' => $headers, 'body' => $body])->getBody()->getContents();
}

}

邮递员的响应为400错误请求,我尝试将其更改为'form_params'和'json'

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

因此,我可以使用此功能

/**
 * @param Request $request
 *
 * @return string
 *
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
public function proxyToExampleServer(Request $request)
{
    $method = $request->getMethod();
    $body = json_decode($request->getContent(), true);
    $path = $request->path() . ($request->getQueryString() ? ('?' . $request->getQueryString()) : '');
    $headers = $request->header();

    try {
        return $this->request($method, $path, ['headers' => $headers, 'json' => $body])->getBody()->getContents();
    } catch (ClientException $exception) {
        return $exception->getResponse();
    }
}