1、使用原生的PHP函数发送GET请求:
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$url = 'http://example.com/api?' . http_build_query($data);
$response = file_get_contents($url);
2、使用原生的PHP函数发送POST请求:application/x-www-form-urlencoded
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents('http://example.com/api', false, $context);
3、使用php发送json格式的post请求
$url = "";
// echo $url;
$postdata = [
"Speed" => 1
];
$jsonData = json_encode([
'Header' => ['a'=>'1'],
'Payload' => $postdata
],JSON_UNESCAPED_UNICODE);
// echo $jsonData;die;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json;charset=utf-8"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 关闭SSL验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
echo 'Response:' . $response;
}
curl_close($ch);