php发送get、post请求的6种方法简明总结

58次阅读
没有评论

共计 1464 个字符,预计需要花费 4 分钟才能阅读完成。

  1. 使用原生的 PHP 函数发送 GET 请求:
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$url = 'http://example.com/api?' . http_build_query($data);
$response = file_get_contents($url);
  1. 使用原生的 PHP 函数发送 POST 请求:
$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);
  1. 使用 cURL 库发送 GET 请求:
$ch = curl_init();
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$url = 'http://example.com/api?' . http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
  1. 使用 cURL 库发送 POST 请求:
$ch = curl_init();
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
  1. 使用 Guzzle 库发送 GET 请求:
$client = new GuzzleHttp\Client();
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$response = $client->get('http://example.com/api', ['query' => $data]);
$body = $response->getBody();
  1. 使用 Guzzle 库发送 POST 请求:
$client = new GuzzleHttp\Client();
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$response = $client->post('http://example.com/api', ['form_params' => $data]);
$body = $response->getBody();

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1464字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)