如何使用Guzzle以JSON格式发送POST请求?

时间:2021-02-13 20:15:34

Does anybody know the correct way to post JSON using Guzzle?

有人知道使用Guzzle发布JSON的正确方法吗?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

I get an internal server error response from the server. It works using Chrome Postman.

我从服务器获得一个内部服务器错误响应。它使用铬邮差工作。

10 个解决方案

#1


143  

For Guzzle 5 & 6 you do it like this:

对于Guzzle 5和6你这样做:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']
]);

Docs

文档

#2


36  

For Guzzle <= 4:

狂饮< = 4:

It's a raw post request so putting the JSON in the body solved the problem

这是一个原始的post请求,因此将JSON放在body中解决了这个问题

$request = $this->client->post($url,array(
                'content-type' => 'application/json'
        ),array());
$request->setBody($data); #set body!
$response = $request->send();

return $response;

#3


24  

The simple and basic way (guzzle6):

简单而基本的方法(guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

为了获得响应状态代码和正文内容,我这样做了:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

#4


21  

$client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

#5


11  

This worked for me (using Guzzle 6)

这对我很有效(使用Guzzle 6)

$client = new Client(); 
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>  
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

#6


4  

This works for me with Guzzle 6.2 :

这对Guzzle 6.2也适用:

$gClient =  new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
                            array(
                                'headers'=>array('Content-Type'=>'application/json'),
                                'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
                                )
                    );

According to the documentation guzzle do the json_encode

根据文档,guzzle做json_encode

#7


0  

The answer from @user3379466 can be made to work by setting $data as follows:

@user3379466的答案可以设置$data如下:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

我们的项目需要的是在json字符串中插入一个变量到数组中,我这样做了(如果这对任何人都有帮助的话):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

有了$existing_variable,比如90210,你会得到:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

同样值得注意的是,您可能还需要设置“Accept”=> '应用程序/json',以避免您所碰到的端点会关心此类问题。

#8


0  

@user3379466 is correct, but here I rewrite in full:

@user3379466是正确的,但我在这里将全文重写:

-package that you need:

 "require": {
    "php"  : ">=5.3.9",
    "guzzlehttp/guzzle": "^3.8"
},

-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):

$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('username@gmail.com', 'password', 'Digest'),)));

$url          = "https://api.yourbaseapiserver.com/incidents.xml";
        
$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>dsss@mail.ca</email></requester>
<description>description2a</description>
</incident>';

    $request = $client->post($url, array('content-type' => 'application/xml',));

    $request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.

    $response = $request->send(); #you must do send() method!
    echo $response->getBody(); #you should see the response body from the server on success
    die;

--- Solution for * Guzzle 6 * --- -package that you need:

---你需要的* Guzzle 6 * --- -包装的解决方案:

 "require": {
    "php"  : ">=5.5.0",
    "guzzlehttp/guzzle": "~6.0"
},

$client = new Client([
                             // Base URI is used with relative requests
                             'base_uri' => 'https://api.compay.com/',
                             // You can set any number of default request options.
                             'timeout'  => 3.0,
                             'auth'     => array('you@gmail.ca', 'dsfddfdfpassword', 'Digest'),
                             'headers' => array('Accept'        => 'application/vnd.comay.v1.1+xml',
                                                'Content-Type'  => 'text/xml'),
                         ]);

$url = "https://api.compay.com/cases.xml";
    $data string variable is defined same as above.


    // Provide the body as a string.
    $r = $client->request('POST', $url, [
        'body' => $data
    ]);

    echo $r->getBody();
    die;

#9


0  

Above answers did not worked for me somehow. But this works fine for me.

以上的回答不知怎么对我不起作用。但这对我来说还行。

 $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

 $request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));

#10


0  

Simply use this it will work

只要使用这个就可以了

   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();

#1


143  

For Guzzle 5 & 6 you do it like this:

对于Guzzle 5和6你这样做:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']
]);

Docs

文档

#2


36  

For Guzzle <= 4:

狂饮< = 4:

It's a raw post request so putting the JSON in the body solved the problem

这是一个原始的post请求,因此将JSON放在body中解决了这个问题

$request = $this->client->post($url,array(
                'content-type' => 'application/json'
        ),array());
$request->setBody($data); #set body!
$response = $request->send();

return $response;

#3


24  

The simple and basic way (guzzle6):

简单而基本的方法(guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

为了获得响应状态代码和正文内容,我这样做了:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

#4


21  

$client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

#5


11  

This worked for me (using Guzzle 6)

这对我很有效(使用Guzzle 6)

$client = new Client(); 
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>  
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

#6


4  

This works for me with Guzzle 6.2 :

这对Guzzle 6.2也适用:

$gClient =  new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
                            array(
                                'headers'=>array('Content-Type'=>'application/json'),
                                'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
                                )
                    );

According to the documentation guzzle do the json_encode

根据文档,guzzle做json_encode

#7


0  

The answer from @user3379466 can be made to work by setting $data as follows:

@user3379466的答案可以设置$data如下:

$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):

我们的项目需要的是在json字符串中插入一个变量到数组中,我这样做了(如果这对任何人都有帮助的话):

$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:

有了$existing_variable,比如90210,你会得到:

echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.

同样值得注意的是,您可能还需要设置“Accept”=> '应用程序/json',以避免您所碰到的端点会关心此类问题。

#8


0  

@user3379466 is correct, but here I rewrite in full:

@user3379466是正确的,但我在这里将全文重写:

-package that you need:

 "require": {
    "php"  : ">=5.3.9",
    "guzzlehttp/guzzle": "^3.8"
},

-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):

$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('username@gmail.com', 'password', 'Digest'),)));

$url          = "https://api.yourbaseapiserver.com/incidents.xml";
        
$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>dsss@mail.ca</email></requester>
<description>description2a</description>
</incident>';

    $request = $client->post($url, array('content-type' => 'application/xml',));

    $request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.

    $response = $request->send(); #you must do send() method!
    echo $response->getBody(); #you should see the response body from the server on success
    die;

--- Solution for * Guzzle 6 * --- -package that you need:

---你需要的* Guzzle 6 * --- -包装的解决方案:

 "require": {
    "php"  : ">=5.5.0",
    "guzzlehttp/guzzle": "~6.0"
},

$client = new Client([
                             // Base URI is used with relative requests
                             'base_uri' => 'https://api.compay.com/',
                             // You can set any number of default request options.
                             'timeout'  => 3.0,
                             'auth'     => array('you@gmail.ca', 'dsfddfdfpassword', 'Digest'),
                             'headers' => array('Accept'        => 'application/vnd.comay.v1.1+xml',
                                                'Content-Type'  => 'text/xml'),
                         ]);

$url = "https://api.compay.com/cases.xml";
    $data string variable is defined same as above.


    // Provide the body as a string.
    $r = $client->request('POST', $url, [
        'body' => $data
    ]);

    echo $r->getBody();
    die;

#9


0  

Above answers did not worked for me somehow. But this works fine for me.

以上的回答不知怎么对我不起作用。但这对我来说还行。

 $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

 $request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));

#10


0  

Simply use this it will work

只要使用这个就可以了

   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();