【发布时间】:2017-02-27 11:16:31
【问题描述】:
我正在尝试将 HTML 表单中的数据发布到 REST API 中,作为参考,可以在此处找到该 API:Gamification Kinben
表单本身现在相当简单,因为目前这是一个概念证明,但在提交时我收到以下错误:
{"content":null,"contentResponseType":"BAD_REQUEST","info":[{"message":": may not be null"},{"message":": may not be null"},{"message":": {API key is not valid}"}]}
HTML 表单
<form method="post" action="#">
<input type="text" id="nickname" name="nickname" placeholder="nickname">
<input type="password" id="password" name="password" placeholder="password">
<input type="text" id="reference" name="reference" placeholder="ref12345">
<input type="text" id="roleIds" name="roleIds" placeholder="3">
<button type="submit" id="submit">Add Player</button>
</form>
PHP 卷曲
<?php
//set empty variable placeholders
$nickname = $password = $reference = $roleIds = "";
//Get data from Form
$nickname = secure_data($_POST['nickname']);
$password = secure_data($_POST['password']);
$reference = secure_data($_POST['reference']);
$roleIds = secure_data($_POST['roleIds']);
//Set API Key
$apiKey = "abc123-this-isa-example-ofthekey23124";
//Strip html and slashes etc
function secure_data($data){
$Sdata = trim($data);
$Sdata = stripslashes($data);
$Sdata = htmlspecialchars($data);
//var_dump($Sdata);
return $Sdata;
}
//Set up POST array
$array = array (
"nickname" => $nickname,
"password" => $password,
"reference" => $reference,
"roleIds" => $roleIds,
"apiKey" => $apiKey,
);
$data_string = json_encode($array);
var_dump ($data_string);
$url = 'serveraddress/gamification_engine/player/';
//Create cURL connection
$curl = curl_init($url);
//set cURL options
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
//Execute cURL
$curl_response = curl_exec($curl);
//Output server response
print_r($curl_response);
//Close cURL connection
curl_close($curl);
?>
【问题讨论】:
-
对不起,我应该提到,API 密钥是有效的,它通过 DHC Restlet 客户端进行 POST 和 GET 工作非常好,我也可以很高兴地使用 API 密钥在 PHP 中发出 GET 请求。