Http get cant take the body

For Joomla! 4.x Coding related discussions, you could also use: http://groups.google.com/group/joomla-dev-general

Moderators: ooffick, General Support Moderators

Forum rules
Forum Rules
Absolute Beginner's Guide to Joomla! <-- please read before posting, this means YOU.
Forum Post Assistant - If you are serious about wanting help, you will use this tool to help you post.
Windows Defender SmartScreen Issues <-- please read this if using Windows 10.
Post Reply
ppanagos
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Wed Jun 07, 2023 2:47 pm

Http get cant take the body

Post by ppanagos » Wed Jun 07, 2023 3:04 pm

Hello, I am using Joomla 4 and I am using Joomla\Http\HttpFactory; and I make a get call like this

Code: Select all

$httpFactory = new HttpFactory();
        $http = $httpFactory->getHttp();
        $response = $http->get("example_url",array("Content-Type" => "application/json","Accept" =>"application/json"));
        $bodyStream = $response->getBody();
        $body = $bodyStream->getContents();
        
My problem is that the variable $body is an empty string and the variable $bodyStream has the following

Code: Select all

object(Laminas\Diactoros\Stream)#181 (2) {
  ["resource":protected]=>
  resource(212) of type (stream)
  ["stream":protected]=>
  string(12) "php://memory"
}
When I hit the url in the browser I get the json I want but i cant take it with the get call.

How can I take the body of the url with the get method of HttpFactory?

SharkyKZ
Joomla! Hero
Joomla! Hero
Posts: 2899
Joined: Fri Jul 05, 2013 10:35 am
Location: Parts Unknown

Re: Http get cant take the body

Post by SharkyKZ » Wed Jun 07, 2023 3:29 pm

The stream probably needs to be rewound before getting contents:

Code: Select all

if ($bodyStream->isSeekable())
{
    $bodyStream->rewind();
}

$body = $bodyStream->getContents();
Or you can use cast to string as a shortcut:

Code: Select all

$body = (string) $bodyStream;
Documentation https://www.php-fig.org/psr/psr-7/#34-p ... minterface

ppanagos
Joomla! Fledgling
Joomla! Fledgling
Posts: 2
Joined: Wed Jun 07, 2023 2:47 pm

Re: Http get cant take the body

Post by ppanagos » Fri Jun 09, 2023 9:07 am

Hello, thank you for the answer.

I did the thing that u mentioned but the result is the same.

Is there anything else to do ?


Post Reply

Return to “Joomla! 4.x Coding”