使用php curl时传递值
我正在尝试请求具有以下详细信息的API: 请求头:使用php curl时传递值,php,php-curl,Php,Php Curl,我正在尝试请求具有以下详细信息的API: 请求头: Content-Type: application/x-www-form-urlencoded apikey: {{Your API Key}} "channel" : "chat", "source" : "xxxxxxx", "destination" : "xxxxxxxx" "src.name"
Content-Type: application/x-www-form-urlencoded
apikey: {{Your API Key}}
"channel" : "chat",
"source" : "xxxxxxx",
"destination" : "xxxxxxxx"
"src.name":"DemoApp"
"message" : {
"isHSM":"false",
"type": "text",
"text": "Hi John, how are you?"
}
请求正文:
Content-Type: application/x-www-form-urlencoded
apikey: {{Your API Key}}
"channel" : "chat",
"source" : "xxxxxxx",
"destination" : "xxxxxxxx"
"src.name":"DemoApp"
"message" : {
"isHSM":"false",
"type": "text",
"text": "Hi John, how are you?"
}
我目前的代码如下:
$payload = [
'channel' => $channel,
'source' => $source,
'destination' => $destination,
'message' => $message,
'src.name' => $appname
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://apiurl/test",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"apikey:" . $apikey,
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
if(curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($curl);
echo $response;
我没有在有效负载中获得正确的消息部分,例如添加isHSM、键入等
我目前的代码是:
$message = array(
'isHSM' => true,
'type' => "text",
'text' => "This is a test"
);
正在请求有关如何在上述curl请求中添加消息负载的帮助…您需要将数组传递到
CURLOPT\u POSTFIELDS
中,以使其自动application/x-www-form-urlencoded
。只需删除http\u build\u query()
函数和相应的头。POST
的方法也是自动设置的
curl_setopt_array($curl, array(
CURLOPT_URL => "https://apiurl/test",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"apikey:" . $apikey
)
));
可能需要将消息转换为JSON字符串
$message = json_encode(array(
'isHSM' => true,
'type' => "text",
'text' => "This is a test"
));