curl 你能在Guzzle POST主体中包含原始JSON吗?

5gfr0r5j  于 2022-11-13  发布在  其他
关注(0)|答案(3)|浏览(135)

这应该很简单,但我花了几个小时来寻找答案,真的卡住了。我正在构建一个基本的Laravel应用程序,并使用Guzzle来替换我目前正在进行的CURL请求。所有的CURL函数都在主体中使用原始JSON变量。
我试图创建一个工作的Guzzle客户端,但服务器响应“无效请求”,我只是想知道是否有什么可疑的事情是怎么回事与JSON我张贴。我开始想知道,如果你不能使用原始JSON在Guzzle POST请求正文?当我从服务器接收到有效的响应时,我知道标头在工作,并且当JSON当前在CURL请求中工作时,我知道JSON是有效的。所以我被卡住了:-(
任何帮助都将不胜感激。

$headers = array(
            'NETOAPI_KEY' => env('NETO_API_KEY'),
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'NETOAPI_ACTION' => 'GetOrder'
        );

    // JSON Data for API post
    $GetOrder = '{
        "Filter": {
            "OrderID": "N10139",
                "OutputSelector": [
                    "OrderStatus"
                ]
        }
    }';

    $client = new client();
    $res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);

    return $res->getBody();
koaltpgm

koaltpgm1#

您可以通过'json'请求选项以JSON格式发送常规数组;这也将自动设置正确的标题:

$headers = [
    'NETOAPI_KEY' => env('NETO_API_KEY'),
    'Accept' => 'application/json',
    'NETOAPI_ACTION' => 'GetOrder'
];

$GetOrder = [
    'Filter' => [
        'OrderID' => 'N10139',
        'OutputSelector' => ['OrderStatus'],
    ],
];

$client = new client();
$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers, 
    'json' => $GetOrder,
]);

请注意,Guzzle应用json_encode()时在后台没有任何选项;如果您需要任何定制,建议您自己完成一些工作

$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers + ['Content-Type' => 'application/json'],
    'body' => json_encode($getOrders, ...),
]);
q9yhzks0

q9yhzks02#

“狂饮7号"
下面的代码对我的原始json输入很有效

$data = array(
       'customer' => '89090',
       'username' => 'app',
       'password' => 'pwd'  
    );
    $url = "http://someendpoint/API/Login";
    $client = new \GuzzleHttp\Client();
    $response = $client->post($url, [
        'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
        'body'    => json_encode($data)
    ]); 
    
    
    print_r(json_decode($response->getBody(), true));

由于某些原因,直到我在响应中使用json_decode,输出才被格式化。

xxslljrj

xxslljrj3#

你可能需要设置正文的mime类型,这可以通过setBody()方法轻松完成。

$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');

相关问题