Skip to content

[8.x] Enable to modify HTTP Client request headers when using beforeSending() callback#42244

Merged
taylorotwell merged 3 commits into
laravel:8.xfrom
ianriizky:8.x
May 3, 2022
Merged

[8.x] Enable to modify HTTP Client request headers when using beforeSending() callback#42244
taylorotwell merged 3 commits into
laravel:8.xfrom
ianriizky:8.x

Conversation

@ianriizky
Copy link
Copy Markdown
Contributor

Basically, I'm trying to add a request header when sending an HTTP request using HTTP Client from Laravel. But I want to make this thing dynamically since it requires the targeted URL as the header data and it will be used in many further HTTP request. So I decide to use the Http::beforeSending() method and take the given Illuminate\Http\Client\Request parameter to get the URL as the example shown below.

<?PHP

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;

Http::beforeSending(function (Request $request, array $options, PendingRequest $pendingRequest) {
    $requestLine = sprintf(
        '%s %s HTTP/%s',
        $request->toPsrRequest()->getMethod(),
        $request->toPsrRequest()->getUri()->withScheme('')->withHost(''),
        $request->toPsrRequest()->getProtocolVersion()
    );

    // this way doesn't work as I mention below.
    $pendingRequest->withHeaders(['Authorization' => 'Bearer '.$requestLine]);

    // this way works, but need some changes in the HTTP client.
    return $request->toPsrRequest()->withHeader('Authorization', 'Bearer '.$requestLine);
})->get('http://foo.com/json');

The problem is the request header wasn't changed at all since the PendingRequest::runBeforeSendingCallbacks() used to run this callback doesn't bring that into the real HTTP request as I expect. Using PendingRequest::withHeaders() also doesn't work because the actual HTTP Request was already created, so any modification that comes from the PendingRequest instance is useless.

This PR will fix that problem, so every registered beforeSending callback on the HTTP Client that returns a GuzzleHttp\Psr7\RequestInterface or Illuminate\Http\Client\Request value will be applied to the HTTP request instance.

@taylorotwell taylorotwell merged commit 6e5e599 into laravel:8.x May 3, 2022
ianriizky added a commit to ianriizky/talenta-api that referenced this pull request May 4, 2022
ianriizky added a commit to ianriizky/beone-sap-service-layer that referenced this pull request May 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants