Jas*_*ill 10 php json curl guzzle
这应该是太简单了,但我花了几个小时寻找答案,我真的被卡住了.我正在构建一个基本的Laravel应用程序,并且正在使用Guzzle来替换我目前正在制作的CURL请求.所有CURL函数都使用正文中的原始JSON变量.
我正在尝试创建一个正常工作的Guzzle客户端,但服务器正在使用"无效请求"进行重新计算,我只是想知道我发布的JSON是否有些可疑.我开始怀疑你是否不能在Guzzle POST请求体中使用原始JSON?我知道标头正在工作,因为我从服务器收到有效的响应,我知道JSON是有效的,因为它当前在CURL请求中工作.所以我卡住了:-(
任何帮助都会非常感激.
$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();
Run Code Online (Sandbox Code Playgroud)
Ja͢*_*͢ck 20
您可以通过'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,
]);
Run Code Online (Sandbox Code Playgroud)
狂饮 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));
Run Code Online (Sandbox Code Playgroud)
由于某些原因,直到我在响应中使用 json_decode,输出才被格式化。