php怎么设置http请求体

36次阅读
没有评论

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

在 PHP 中,可以使用以下两种方法设置 HTTP 请求体:

  1. 使用 file_get_contents() 函数发送 POST 请求,并设置请求体数据。
$url = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$options = array(
'http' => array(
'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
'method'  => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
  1. 使用 cURL 库发送 POST 请求,并设置请求体数据。
$url = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$result = curl_exec($ch);
curl_close($ch);

注意:以上示例中的 $data 数组为请求体数据,可以根据需要进行修改。http_build_query()函数用于将数组转换为 URL 编码的字符串。

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

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