简体   繁体   中英

Laravel Guzzle post request

I have trouble setting my Guzzle headers.

try {
    $res = $client->post($apiURL,
        [
            'headers' => [
                'Content-Type' => 'application/json',
                'accept' => 'application/json',
                'Authorization' => 'Bearer ' . $token,
            ],
            'body' => \GuzzleHttp\json_encode([
                'query' => 'xxxyyy'
            ])
        ]
    );
} catch (\GuzzleHttp\Exception\ClientException $e) {
    dd($e->getResponse()->getBody()->getContents());
}

I get response from server that I need to check my access token, though it passes fine in the Postman when doing the same request. When checking Chrome inspector I am getting

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

I tried setting headers directly in the new Client() constructor but I get the same response.

Package used: use GuzzleHttp\\Client;

It's not clear from your question, what the problem is.

In general, use the form_params option to pass application/x-www-form-urlencoded body and the json option to pass application/json body. The Content-Type header will be set up automatically.

It seems that need to send a form, but you are sending a JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM