Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guzzle ver 6 post method is not woking

Tags:

php

guzzle

is working in postman (raw format data with with application/json type) with guzzle6

url-http://vm.xxxxx.com/v1/hirejob/
{
        "company_name":" company_name",
        "last_date_apply":"06/12/2015",
        "rid":"89498"
}

so am getting response 201 created
but in guzzle

    $client = new Client();
    $data = array();
    $data['company_name'] = "company_name";
    $data['last_date_apply'] = "06/12/2015";
    $data['rid'] = "89498";
    $url='http://vm.xxxxx.com/v1/hirejob/';
    $data=json_encode($data);
    try {
            $request = $client->post($url,array(
                    'content-type' => 'application/json'
            ),array());

        } catch (ServerException $e) {
          //getting GuzzleHttp\Exception\ServerException Server error: 500
        }

i am getting error on vendor/guzzlehttp/guzzle/src/Middleware.php

line no 69

 ? new ServerException("Server error: $code", $request, $response)
like image 596
RahulG Avatar asked Feb 09 '23 20:02

RahulG


2 Answers

You're not actually setting the request body, but arguably the easiest way to transfer JSON data is by using the dedicated request option:

$request = $client->post($url, [
    'json' => [
        'company_name' => 'company_name',
        'last_date_apply' => '06/12/2015',
        'rid' => '89498',
    ],
]);
like image 87
Ja͢ck Avatar answered Feb 12 '23 10:02

Ja͢ck


You need to use json_encode() JSON_FORCE_OBJECT flag as the second argument. Like this:

$data = json_encode($data, JSON_FORCE_OBJECT);

Without the JSON_FORCE_OBJECT flag, it will create a json array with bracket notation instead of brace notation.

Also, try sending a request like this:

$request = $client->post($url, [
    'headers' => [ 'Content-Type' => 'application/json' ],
    'body' => $data
]);
like image 42
Ben T Avatar answered Feb 12 '23 10:02

Ben T