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

时间:2014-03-07 08:06:37

标签: php postman guzzle

是否有人知道使用post的{​​{1}} JSON的正确方法?

Guzzle

我从服务器收到$request = $this->client->post(self::URL_REGISTER,array( 'content-type' => 'application/json' ),array(json_encode($_POST))); 响应。它使用Chrome internal server error

14 个答案:

答案 0 :(得分:210)

Guzzle 5& 6 你这样做:

use GuzzleHttp\Client;

$client = new Client();

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

Docs

答案 1 :(得分:39)

对于 Guzzle< = 4

这是一个原始的帖子请求,因此将JSON放入正文中解决了问题

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

return $response;

答案 2 :(得分:34)

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

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

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

要获取响应状态代码和正文的内容,我这样做了:

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

答案 3 :(得分:24)

$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();

答案 4 :(得分:21)

这对我有用(使用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());

答案 5 :(得分:7)

这适用于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')
                                )
                    );

根据文档guzzle做json_encode

答案 6 :(得分:4)

$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);

$response = $client->post('/save', [
    'json' => [
        'name' => 'John Doe'
    ]
]);

return $response->getBody();

答案 7 :(得分:1)

Php版本:5.6

Symfony版本:2.3

枪口:5.0

我最近有过使用Guzzle发送json的经验。我使用的是Symfony 2.3,所以我的耗时版本可能会老一些。

我还将展示如何使用调试模式,您可以在发送请求之前看到请求,

当我发出如下所示的请求时,得到了成功的响应;

use GuzzleHttp\Client;

$headers = [
        'Authorization' => 'Bearer ' . $token,        
        'Accept'        => 'application/json',
        "Content-Type"  => "application/json"
    ];        

    $body = json_encode($requestBody);

    $client = new Client();    

    $client->setDefaultOption('headers', $headers);
    $client->setDefaultOption('verify', false);
    $client->setDefaultOption('debug', true);

    $response = $client->post($endPoint, array('body'=> $body));

    dump($response->getBody()->getContents());

答案 8 :(得分:0)

@ user3379466的答案可以通过设置$data来实现,如下所示:

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

我们的项目需要将变量插入到json字符串中的数组中,我的操作如下(如果这有助于任何人):

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

所以$existing_variable就是90210,你得到:

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

另外值得注意的是,您可能还想设置'Accept' => 'application/json',以防您遇到的端点关心此类事情。

答案 9 :(得分:0)

@ 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;

---解决方案 * 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;

答案 10 :(得分:0)

以上答案对我不起作用。但这对我来说很好。

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

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

答案 11 :(得分:0)

只需使用它即可使用

   $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();

答案 12 :(得分:0)

<div id="check" class="service_name">
    <label><input type="checkbox" name="services" value="sharjah"> Sharjah</label><br>
    <label><input type="checkbox" name="services" value="dubai">dubai</label><br>
    <label><input type="checkbox" name="services" value="abu dhabi">abu dhabi</label><br>
    <label><input type="checkbox" name="services" value="musaffa">musaffa</label>
</div>

请参见Docs

答案 13 :(得分:0)

我使用以下非常可靠的代码。

JSON数据在$ request参数中传递,特定的请求类型在$ searchType变量中传递。

该代码包含一个陷阱,用于检测并报告未成功或无效的调用,然后将返回false。

如果调用成功,则json_decode($ result-> getBody(),$ return = true)返回结果数组。

    public function callAPI($request, $searchType) {
    $guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);

    try {
        $result = $guzzleClient->post( $searchType, ["json" => $request]);
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error .= '<pre>'.print_r($request, $return=true).'</pre>';
        $error .= 'No returnable data';
        Event::logError(__LINE__, __FILE__, $error);
        return false;
    }
    return json_decode($result->getBody(), $return=true);
}
相关问题