Body of Async request in Guzzle - php

I want to send a asynchronous request using Guzzle PHP HTTP client, however it seems it only allows body to be a string .
I have header variable as
$headers = [
"Authorization" : $token
];
Similarly I want to have body also as array
$body = [
"x"=>$y,
"y"=>$z,
]
I make a request variable as
$request = new \GuzzleHttp\Psr7\Request(
'POST',
'API_URL',
$headers,
$body
);
However I get InvalidArgumentException Invalid resource type: array error, but on trying $body="some useless string", the request is sent to the server, but get error as body doesn't have appropriate parameters .
How can I set Body here as an array/(nested array if required) with my desired keys.

Use json_encode function, pass your body array by
$request = new \GuzzleHttp\Psr7\Request(
'POST',
'API_URL',
$headers,
json_encode($body)
);

Related

Set request content to test in symfony

I have to set a test to check the user registragion with an API , but I'm not sure how to set the content, its has to had a header with the token named x-auth-tokenand the body with aform-data` param named data that contains json-string
public function testUserRegister(){
$client = static::createClient();
$server = array('x-auth-token' => '...');
$client->request(Request::METHOD_POST, self::$uri, [], [], $server);
$response = $client->getResponse();
self::assertEquals( Response::HTTP_CREATED, $response->getStatusCode());
}
When I check on the debug ther is no x-auth-token on the headers
Use third parameter of $client->request method to pass your data.
If you want to send payload as form data with JSON, you need to do something like this:
$client->request(..., ..., ['data' => json_encode(...)], ...);
Keep in mind that you maybe need to set correct Content-Type in header (application/x-www-form-urlencoded).

PHP file_get_contents() is ignoring the request body when making a GET request

I am trying to make a simple HTTP GET request to query Elasticsearch. The Elasticsearch syntax allow the use of a request body in a GET request to add addition query options. I am using the PHP function file_get_contents() to make the GET request.
The problem is that file_get_contents() seems to be ignoring the body of the request when making a GET request yet it works fine when using a POST request instead.
How can I get file_get_contents() to process the body of the GET request correctly?
The code I am using is shown below.
Note that :
I want to use file_get_contents() to do this, NOT php cURL, php Request2, or the elasticsearch-php library
I would like to keep this as a GET request, changing it to a POST request instead is not what I am after
Thanks in advance!
$url = "example-elasticsearch-url-here.com/index/_search";
$body=<<<EOD
{
"_source": ["email"],
"size":10,
"query":{
"match_all" : {}
}
}
EOD;
$contextData = array (
'method' => 'GET',
'header' => "Content-Type: application/json\r\n".
'ssl'=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
'content'=> $body
);
$context = stream_context_create (array ( 'https' => $contextData ));
try {
$result = file_get_contents ($url,false,$context);
} catch (Exception $e) {
$result = false;
}
echo $result;
Does it work, if you use http instead of https as key name in $context?

guzzle getbody function accessing the diffrenet elements of response

i am using guzzle to post some data to some api and recive some data back here is my code :
$response = $client->request('POST', 'http://url/api/v1/transaction/Verify', [
'headers' => ['Content-Type' => 'application/json'],
'body' => '{
"tn":"1905463527",
}'
]);
$responebody = $response->getBody();
i exacly dont know if i am getting string or object when ever i use getbody of guzzle but here is what i get when i echo the response :
{"errorCode":null,"errorMessage":"Canceled by user.","succeed":false,"tn":1905463527,"verifyCount":35,"amount":10000}
now here for example i want to access the "succeed " element and i want to know how can i access to check if it is true or not ,
You should check the Content-Type header and if it's application/json you can run json_decode on the body. Take this as an example
if ($response->getContentType() == 'application/json') {
$responseBody = json_decode($response->getContent());
// now you can access $responseBody->succeed
...
}

Send Body as raw using Guzzle

I am trying to use Guzzle to send POST request to my web service. this service accepts body as raw. It works fine when I use postman but I doesn't using Guzzle. when using Guzzle, I get only the webservice description as I put the web service URL in the browser.
here is my code:
$body = "CA::Read:PackageItems (CustomerId='xxxxxx',AllPackages=TRUE);";
$headers = [
....
....
];
$client = new Client();
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',$headers,$body);
echo $body = $response->getBody();
seems headers or body doesn't pass through.
Try like this
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);
I have recently had to implement Guzzle for the first time and it is a fairly simple library to use.
First I created a new Client
// Passed in our options with just our base_uri in
$client = new Client(["base_uri" => "http://example.com"]);
I then created a POST request, not how I am using new Request instead of $client->request(... though. This doesn't really matter to much that I've used new Request though.
// Create a simple request object of type 'POST' with our remaining URI
// our headers and the body of our request.
$request = new Request('POST', '/api/v1/user/', $this->_headers, $this->body);
so in essence it would look like:
$request = new Request('POST', '/api/v1/user/', ['Content-Type' => "application/json, 'Accept' => "application/json"], '{"username": "myuser"}');
$this->headers is a simple key-value pair array of our request headers making sure to set the Content-Type header and $this->body is a simple string object, in my case it forms a JSON body.
I can simply then just call the $client->send(... method to send the request like:
// send would return us our ResponseInterface object as long as an exception wasn't thrown.
$rawResponse = $client->send($request, $this->_options);
$this->_options is a simple key-value pair array again simple to the headers array but this includes things like timeout for the request.
For me I have created a simple Factory object called HttpClient that constructs the whole Guzzle request for me this is why I just create a new Request object instead of calling $client->request(... which will also send the request.
What you essentially need to do to send data as raw is to json_encode an array of your $data and send it in the request body.
$request = new Request(
'POST',
$url,
['Content-Type' => 'application/json', 'Accept' => 'application/json'],
\GuzzleHttp\json_encode($data)
);
$response = $client->send($request);
$content = $response->getBody()->getContents();
Using guzzle Request GuzzleHttp\Psr7\Request; and Client GuzzleHttp\Client

Specify raw body of a POST request with Guzzle

With Guzzle (version 3), I'd like to specify the body of a POST request in "raw" mode. I'm currently trying this:
$guzzleRequest = $client->createRequest(
'POST',
$uri,
null,
'un=one&deux=two'
);
But it kind of doesn't work. If I dump my $guzzleRequest I can see that postFields->data is empty. Using $guzzleRequest->setBody() afterwards doesn't help.
However if I specify the body as ['un'=>'one', 'deux'=>'two'], it works as expected.
How can I specify the body of the request as 'un=one&deux=two'?
First I would highly recommend that you upgrade to Guzzle 6 as Guzzle 3 is deprecated and EOL.
It has been a long time since I used Guzzle 3 but I do believe you want the following:
$request = $client->post(
$uri,
$header = [],
$params = [
'un' => 'one',
'deux' => 'two',
]);
$response = $request->send();
Guzzle will automatically set the Content-Type header.
More information is available with the Post Request Documentation.
In response to your comment:
$request = $client->post(
$uri,
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'],
EntityBody::fromString($urlencodedstring)
)
For this, reference: EntityBody Source and RequestFactory::create()

Categories