【问题标题】:PHP: Guzzle Client - Proxy request to different serverPHP:Guzzle 客户端 - 对不同服务器的代理请求
【发布时间】:2018-11-14 10:02:36
【问题描述】:

所以,我只是想将所有请求代理到不同的服务器。

我希望一切都一样,除了我想更改基本 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();
}

}

Postman 中的响应是 400 Bad Request,我已尝试更改为 'form_params' 和 'json'

有什么想法吗?

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

    所以,我得到了它与这个功能一起工作

    /**
     * @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();
        }
    }
    

    【讨论】:

    • 我无法使用它上传文件。文件上传与此有关,否则我们必须进行其他配置
    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多