繁体   English   中英

使用PHP cURL将HTML FORM数据发布到REST API

[英]POST HTML FORM data to REST API using PHP cURL

我正在尝试将数据从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的URL

<?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密钥。

{API密钥无效}

您的API密钥无效,或者您没有将其正确发送到API

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM