Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用Guzzle发送JSON格式的POST请求?_Php_Postman_Guzzle - Fatal编程技术网

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

Php 如何使用Guzzle发送JSON格式的POST请求?,php,postman,guzzle,Php,Postman,Guzzle,有人知道使用Guzzle发布JSON的正确方法吗 $request = $this->client->post(self::URL_REGISTER,array( 'content-type' => 'application/json' ),array(json_encode($_POST))); 我从服务器收到内部服务器错误响应。它使用ChromePostman进行工作,对于Guzzle,可以通过设置$data使@user33

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

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

我从服务器收到
内部服务器错误
响应。它使用Chrome
Postman

进行工作,对于Guzzle,可以通过设置
$data
使@user3379466的答案生效,如下所示:

$data = "{'some_key' : 'some_value'}";
我们的项目需要在json字符串内的数组中插入一个变量,我的做法如下(以防这对任何人都有帮助):

因此,假设
$existing_variable
为90210,您可以得到:

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

另外值得注意的是,您可能还需要设置
'Accept'=>'application/json'
,以防您正在访问的端点关心此类事情。

对于Guzzle 5、6和7,您可以这样做:

$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();
use GuzzleHttp\Client;

$client = new Client();

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

@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=
事件标题2a
中等
dsss@mail.ca
说明2a
';简单而基本的方法(guzzle6):

为了获取响应状态代码和正文内容,我执行了以下操作:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';
echo“”。变量导出($response->getStatusCode(),true)。“”;
回显“”。变量导出($response->getBody()->getContents(),true)。“”;

不知怎么的,上面的答案对我不起作用。但这对我来说很好

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

这适用于Guzzle 6.2:

   $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();
根据guzzle文档,json_编码对我有用吗(使用guzzle 6)


只要用这个,它就会工作

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    'json' => ['foo' => 'bar']
]);

您可以使用硬编码的
json
属性作为键,也可以方便地使用
GuzzleHttp\RequestOptions::json
常量

下面是使用硬编码的
json
string的示例

    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);
}
请参阅。

Php版本:5.6

Symfony版本:2.3

狂饮:5.0

我最近有一次用Guzzle发送json的经验。我使用Symfony 2.3,所以我的guzzle版本可以稍微旧一点

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

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


我使用了以下工作非常可靠的代码

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

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

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

公共函数callAPI($request,$searchType){
$guzzleClient=新的GuzzleHttp\Client([“基本uri”=>”https://example.com"]);
试一试{
$result=$guzzleClient->post($searchType,[“json”=>$request]);
}捕获(例外$e){
$error=$e->getMessage();
$error.=''.print\u r($request,$return=true)。'';
$error.='无可返回数据';
事件::logError(_行_,_文件_,$error);
返回false;
}
返回json_decode($result->getBody(),$return=true);
}


请求似乎没问题。。。您是否检查了$\u POST的内容,以确保在编码之前确实获得了值var_dump($_POST)根据docs now,您可以使用@davykiash所说的,
'json'=>$data
:只是一个提示。。。您可以使用
json\u encode
简化
$data
$data=json\u encode(数组('collection'=>$existing\u变量))这不再适用于GuzzleHttp@Charlie有正确的答案我想我们只需要在问题中指定Guzzle的版本。如果你想在Guzzle 6中设置内容类型标题,你可以这样做:
$client->post($url,['body'=>$string,'headers'=>['content-type'=>'application/json']])我用Guzzle3试过了,即使它是文档中提到的方式,它也不起作用:,已经两天了,我试图解决这个问题,但是在Vainaccord,根据文档,你可以使用@davykiash所说的,
'json'=>$data
:这是否也设置了正确的标题?我认为,
['json'=>$body]
是更好的方法,正如Michael的回答所提到的仅适用于Guzzle 5.3。它已在v6中删除。David是正确的。这是因为PSR-7的实施。改为使用
json\u decode()
。当您必须发送头,例如git的授权令牌时,这将不起作用。您必须实例化一个请求对象并使用send或Request函数这是正确的方法()建议对选项数组键使用
RequestOptions
常量(
GuzzleHttp\RequestOptions::JSON
)-它使打字错误更容易被发现,因为它们突然变成了通知,而不仅仅是等待引起麻烦的沉默的错误。@MichalGallovic也是这样。使用常量的目的是避免输入错误。使用一个不存在的常量会引起错误,但是发送一个无用的选项(例如
jsson
)不会引起任何错误,而且您可能需要一些时间来查找您的输入错误。我在四处寻找了一个小时的答案。为什么文档(尤其是《快速设置指南》)中没有这一点?疯了@giovannipds GuzzleHttp\RequestOptions::JSON是“JSON”的别名,两者都可以。这确实是一种简单易行的方法。解决了设置正文和标题的问题。非常感谢当被接受的答案不适用时,这个答案对我有效。我使用了这个的一个变体。我自己创建了
客户端
,并将标题添加到
$Client->post()
调用中。谢谢。在其他任何地方都找不到适用于旧版php5.3项目的guzzle3解决方案,希望看到它换行。我也希望您的guzzle6,因为它可以节省我很多时间。
$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')
                                )
                    );
$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());
   $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();
$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);

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

return $response->getBody();
use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    'json' => ['foo' => 'bar']
]);
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());
    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);
}