0
votes

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.

3

3 Answers

1
votes

Try like this

$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);
2
votes

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.

0
votes

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