cURL -d 开关:如何在 guzzle 请求中使用它



我正在学习使用API。它们提供了以下身份验证代码的示例:

curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "   {"Username": "the_username",
"Password": "the_password"}
" "https://someurl.someapi.com:443/api/Login/Authenticate"

但是,我需要通过 Guzzle 请求重现这一点。这是我一直在尝试的

$headers = [
"Content-Type" =>  "application/json",
"Accept" => 'application/json -d " {"Username": "the_username", "Password": "the_password" }" ',
];
//    $headers = [
//       "Content-Type" =>  "application/json"
//    ];

$extra_data = ["proxy"    => $proxy,
"headers"  => $headers ];

// Defining the Guzzle Client to communicate with Legacy.com 
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/Login/Authenticate',
// You can set any number of default request options.
'timeout'  => 10.0,
]);

try {
$response = $client->request('POST', '', $extra_data);
}  

但是,无论我尝试什么(这是我最近一次失败的尝试(,除了代码 400 错误之外,我什么也得不到。

所以我终于想出了怎么做:

这段代码有效!

$str = json_decode('{ "Username": "' . $username . '", "Password": "' . $password  . '"}',true);

var_dump($str);

if ($str == NULL) return;

$url_authenticate = "Login/Authenticate";
$extra_data = ["proxy"    => $proxy,
"json"     => $str ];

// Defining the Guzzle Client to communicate with Legacy.com 
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/',
// You can set any number of default request options.
'timeout'  => 10.0,
]);

try {
$response = $client->request('POST', $url_authenticate, $extra_data);
}   
catch (Exception $e) {
echo 'Exception: ' . $e->getResponse()->getStatusCode() .  "n";
exit;
}      

$body = $response->getBody();
echo $body;   

关键是使用 json 字段 int 额外的数据并使用 json_decode 将 json 转换为 php 数组。我希望这对其他人有所帮助

最新更新