Gzzle ver 6 post method is not woking

works in postman (raw format data using application / json type) with guzzle6

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

      

this is how the answer is 201

but in wzzle

    $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 number 69

 ? new ServerException("Server error: $code", $request, $response)

      

+3


source to share


2 answers


You are not actually setting the request body, but perhaps the simplest way to pass JSON data is using the custom request option:



$request = $client->post($url, [
    'json' => [
        'company_name' => 'company_name',
        'last_date_apply' => '06/12/2015',
        'rid' => '89498',
    ],
]);

      

+6


source


You need to use the 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 a note bracket instead of brace notation.



Also try sending your request like this:

$request = $client->post($url, [
    'headers' => [ 'Content-Type' => 'application/json' ],
    'body' => $data
]);

      

0


source







All Articles