使用身份验证

时间:2017-01-17 06:56:01

标签: php json curl guzzle

我第一次使用guzzle。任何人都可以告诉我如何为此请求编写Guzzle电话。

curl -X POST -u username:password -H "Content-Type: application/json" https://xyz/api/v1/accounts.json -d '{"user":{"username":"test","password":"xyz","first_name":"test","last_name":"test","email":"test@test.com","roles":["Administrator"]}}'

我在卷曲请求的-u中遇到问题。

I have written this code.
$response = $client->post($url, [
    'headers' => ['Content-type' => 'application/json'],
    'auth' => ['username:password'],
    'json' => [
        'username' => 'test'
    ],
]);
$results = $response->json();

我已尝试this但无法调用API

任何建议或帮助。

1 个答案:

答案 0 :(得分:9)

根据docs基本身份验证应使用两个元素的数组(登录名和密码)指定:

$client = new GuzzleHttp\Client();
$url = "//xyz/api/v1/accounts.json";
        $response = $client->post($url, [
            'headers' => ['Content-type' => 'application/json'],
            'auth' => [
                'test', 
                'xyz'
            ],
            'json' => [
                "username"=>"xyz",
                "password"=>"xyz",
                "first_name"=>"test",
                "last_name"=>"test",
                "email"=>"test@test.com",
                "roles"=>"Administrator"
            ], 
        ]);