Ad

Guzzle Http And Laravel Http Post Method Replace With Get Method. 405 Method Not Allowed

- 1 answer

Some information about the problem:

  • I create guzzle client using POST method but it replaced to GET method.
  • I try to use Illuminate\Support\Facades\Http on Laravel 7.x but get the same error.
  • The API server is Django Rest Framework.
  • I got 405 Method Not Allowed response.

My code using guzzle:

public static function post($url, $headers, $body)
{
    $client = new Client([
        'headers' => $headers
    ]);

    $response = collect();

    try {
        $response->code = 200;
        $response->body = json_decode($client->post($url, $body)->getBody()->getContents());
    } catch (RequestException $e) {
        $response->code = $e->getCode();
        $response->body = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : $e->getMessage();
        $response->url = $url;
    }

    return $response;
}

public static function posting()
{
    $url = 'http://xapi-staging.uii.ac.id';
    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => ""
    ];
    $body = [
        'form_params' => [
            "parameter" => "value"
        ]
    ];

    return static::post($url, $headers, $body);
}

dd(static::posting());

I use both form_params and json but still get the same error.

Then I use Laravel Illuminate\Support\Facades\Http

Http::withHeaders([
    'Authorization' => ""
])->post('http://xapi-staging.uii.ac.id', [
    "parameter" => "value",
]);

see Illuminate\Support\Facades\Http doc at : https://laravel.com/docs/7.x/http-client#request-data

Result using Laravel Illuminate\Support\Facades\Http

enter image description here

The method is GET instead of POST

My route:

enter image description here

I use Postman and curl. It works! damn.

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://xapi-staging.uii.ac.id",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>"{\n    \"parameter\": \"value"",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey..",
    "Content-Type: text/plain"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
Ad

Answer

The problem is... You should use https:// instad of http://

Ad
source: stackoverflow.com
Ad