我正在尝试使用cURL& amp;创建API。 JSON。 现在在我的第一个PHP文件中,我将数据作为JSON数据发送,如下所示:
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
但在我的SERVER上,当我显示(使用var_export()
)值时,我收到此请求:
public function login()
{
$client_data = $this->input->post();
var_export($client_data);
}
错误:
阵列(“” {\ u201cRequest \即表示: \ u201cLogin \即表示, \ u201cUsername \即表示: \ u201cBIZRTC \即表示, \ u201cAPIAccessKey \即表示: \ u201cAW342FFGRTR56RTH \ u201d, \ u201cGMT-Timestamp \ u201d:_ \ u201c1489670000 \ u201d}“'=&gt;'',0 =&gt;'',)
即使我在那里解码它,我仍然得到\u
。此外,我不明白如何附加这些值:在开始时:'"{\\u201c
和后面的\\u201d}"' => '', 0 => '',
。
这些价值观是什么?
如何解码此JSON?
我是否向服务器发布了正确的数据?
更新了代码
Client.php
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
Server.php
public function login()
{
var_export($_POST);
}
答案 0 :(得分:2)
您需要在json_encode
中提供数组,而不是字符串。
替换:
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
要强>
$field_string= '{
"Request": "Login",
"Username": "anonymous",
"APIAccessKey": "AW342FFGRTR56RTH",
"GMT-Timestamp": "1489670000"
}';
代码中的问题:
json
。”
中的引号(json
)无效。json_encode
中传递字符串。答案 1 :(得分:1)
这是因为下面的行
length
假设是这样的
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
答案 2 :(得分:1)
如果您将json字符串存储在变量中,那么您不需要json_encode()
,因为它用于将数组转换为json字符串。
$field_string = '{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}';
$json = $field_string;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);