如何在laravel中使用枪口发布方法发送变量

时间:2019-05-27 08:33:00

标签: php laravel guzzle

我有一个api,我需要向其中发送一些数据,并且我正在使用guzzle进行处理,所以这是我的代码:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => '{
        "Amount":"i want to send $amount here",
        "something":"1",
        "Description":"desc",
        }'
    ]);

所以一切都很好,并且正在发送静态数据,但是我想知道如何发送变量。

5 个答案:

答案 0 :(得分:5)

您可以像这样在form_params参数中绑定数据

lambda s: tuple(re.split("\\\\n| ", s))

希望这对您有用。

答案 1 :(得分:1)

通过量变量,如下所示:

$amount = $request->get('amount');
    $client = new \GuzzleHttp\Client();
    $requestapi = $client->post('http://url/api/v1/Transaction/GetTransactionNumber', [
        'headers' => ['Content-Type' => 'application/json'],
        'form_params' => '{
        "Amount": '. $amount .'
        "something":"1",
        "Description":"desc",
        }'
    ]);

答案 2 :(得分:1)

金额可以传递到数组中,然后您可以使用``json_encode''来对json进行编码

希望这对您有用。

$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url   = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data   = [
            "amount"      => $amount,
            "something"   => "1",
            "description" => "desc",
          ];

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

答案 3 :(得分:0)

您可以尝试使用Guzzle json 选项:

$amount = $request->get('amount');

$client = new \GuzzleHttp\Client();

$response = $client->post(
    'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber', 
    [
        GuzzleHttp\RequestOptions::JSON => [
            'Amount' => $amount,
            'something' => '1',
            'Description' => 'desc',
        ]
    ]
);

检查枪口手册-http://docs.guzzlephp.org/en/stable/request-options.html#json

答案 4 :(得分:-1)

您应使用json_encode对正文进行编码:

$requestapi = $client->post(
    'http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber',
    [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'Amount' => $amount,
            'something' => 1,
            'Description' => 'description',
        ])
    ]
);