php 您可以在 Guzzle POST Body 中包含原始 JSON 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31087814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you include raw JSON in Guzzle POST Body?
提问by Jason Hill
This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment. All the CURL functions utilise raw JSON variables in the body.
这应该很简单,但我花了几个小时寻找答案并且真的被卡住了。我正在构建一个基本的 Laravel 应用程序,并且正在使用 Guzzle 来替换我目前正在发出的 CURL 请求。所有 CURL 函数都使用主体中的原始 JSON 变量。
I am trying to create a working Guzzle client but the server is respsonding with 'invalid request' and I am just wondering if something fishy is going on with the JSON I am posting. I am starting to wonder if you can not use raw JSON in the Guzzle POST request body? I know the headers are working as I am receiving a valid response from the server and I know the JSON is valid as it is currently working in a CURL request. So I am stuck :-(
我正在尝试创建一个工作的 Guzzle 客户端,但服务器正在响应“无效请求”,我只是想知道我发布的 JSON 是否有可疑之处。我开始怀疑您是否不能在 Guzzle POST 请求正文中使用原始 JSON?我知道标头正在工作,因为我收到了来自服务器的有效响应,并且我知道 JSON 是有效的,因为它目前正在 CURL 请求中工作。所以我被卡住了:-(
Any help would be sooo greatly appreciated.
任何帮助将不胜感激。
$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();
回答by Ja?ck
You can send a regular array as JSON via the 'json'
request option; this will also automatically set the right headers:
您可以通过'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,
]);
回答by user2479930
You probably need to set the body mime type. This can be done easily using the setBody() method.
您可能需要设置 body mime 类型。这可以使用 setBody() 方法轻松完成。
$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');