0
比方說,我有一個正在運行的服務的API,響應就像一個網址:REST API服務:如何通過PHP curl正確調用它?
http://example.com/param/1
這是對GET和POST動詞擔任。 Param = 1是參數
如何正確執行curl請求以傳遞參數(POST)?
如果我瀏覽:http://example.com/param/1 我會回來預期的響應(GET)
但如果我這樣做,這是行不通的:
$service_url = 'http://example.com/';
$curl = curl_init($service_url);
$curl_post_data = array('param'=>1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
即使改變它像如下因素將無法正常工作:
$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
這不是工作:但我想它仍然是一個GET
$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);
不,不是。 param = 1是要傳遞的參數...您列出的後置字段不是必需的(param1,param2 ....) – koalaok