🗣 Wd提问: PHPHTTP客户端源码
🤖 Ai回答: 以下是一个简单的 PHP HTTP 客户端实现,支持 GET 和 POST 请求,使用 `cURL` 扩展(推荐)或 `file_get_contents`(适用于简单场景):
---
✅ 推荐方式:使用 cURL(功能强大、稳定)
```php
<?php
class HttpClient {
private $ch;
public function __construct() {
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->ch, CURLOPT_TIMEOUT, 30);
curl_setopt($this->ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
}
public function get($url, $headers = []) {
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_HTTPGET, true);
$this->setHeaders($headers);
return $this->execute();
}
public function post($url, $data = [], $headers = []) {
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_POST, true);
if (is_array($data)) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($data));
} else {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);
}
$this->setHeaders($headers);
return $this->execute();
}
private function setHeaders($headers) {
if (!empty($headers)) {
curl_setopt($this->ch, CURLOPT_HTTPHEADER, array_map(function($k, $v) { return "$k: $v"; }, array_keys($headers), array_values($headers)));
}
}
private function execute() {
$response = curl_exec($this->ch);
$httpCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
$error = curl_error($this->ch);
curl_close($this->ch);
if ($error) {
throw new Exception("cURL error: " . $error);
}
return [
'body' => $response,
'status_code' => $httpCode,
'headers' => $this->getHeaders()
];
}
private function getHeaders() {
// 获取响应头(可选)
$headerSize = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
$headerText = substr(curl_getinfo($this->ch, CURLINFO_HEADER_OUT), 0, $headerSize);
$headers = [];
foreach (explode("\r\n", $headerText) as $line) {
if (strpos($line, ':') !== false) {
list($key, $value) = explode(':', $line, 2);
$headers[trim($key)] = trim($value);
}
}
return $headers;
}
public function __destruct() {
if ($this->ch) {
curl_close($this->ch);
}
}
}
// 使用示例:
$client = new HttpClient();
try {
// GET 请求
$result = $client->get('https://httpbin.org/get', ['Accept' => 'application/json']);
echo "Status: " . $result['status_code'] . "\n";
echo "Body:\n" . $result['body'] . "\n";
// POST 请求
$postResult = $client->post('https://httpbin.org/post', ['name' => 'John', 'age' => 30], ['Content-Type' => 'application/x-www-form-urlencoded']);
echo "POST Status: " . $postResult['status_code'] . "\n";
echo "POST Body:\n" . $postResult['body'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
```
---
✅ 简易方式:使用 file_get_contents(仅限简单场景)
```php
<?php
function simpleGet($url, $headers = []) {
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", $headers),
'timeout' => 30
]
]);
$content = @file_get_contents($url, false, $context);
if ($content === false) {
throw new Exception("Failed to fetch URL: $url");
}
return $content;
}
// 示例
try {
$res = simpleGet('https://httpbin.org/get', ['User-Agent: MyClient/1.0']);
echo $res;
} catch (Exception $e) {
echo $e->getMessage();
}
```
---
📌 注意事项:
- `cURL` 支持 HTTPS、代理、认证、Cookie 等高级功能。
- `file_get_contents` 更轻量,但不支持 HTTPS 证书验证等安全特性(需开启 `allow_url_fopen` 并配置 SSL)。
- 建议在生产环境中使用 `cURL`。
- 可封装为类或工具函数,便于复用。
---
✅ 如需更复杂功能(如异步请求、重试机制、自动 JSON 解析等),可基于以上代码扩展,或引入 Guzzle 等第三方库(推荐用于项目开发)。
---
如果你需要支持特定协议(如 WebSocket、HTTP/2)、SSL 验证、超时重试、日志记录等功能,请告诉我,我可以为你定制更完整的版本。
📣 商家广告:





0
IP地址: 59.34.159.27
搜索次数: 0
提问时间: 2025-11-21 18:53:53
🛒 域名购买:
hc.gs
q-u.com.cn
xf.gs
010.hk
06.gold
dk.gs
souru.com.cn
9-9.net
z-u.net
65.com.hk
❓️ 热门提问:
hkt域名
恒温恒湿机柜
借钱申请入口
免费域名注册国外
ip对应域名查询
域名如何使用
怎么申办邮箱域名
idc的相关技术
真正的免费vps
后台挂机
豌豆Ai站群搜索引擎系统
🌐 域名评估:
iw.gs
zz.sc.cn
vivo.hi.cn
yu7.hn.cn
xphone.cab
nggl.cn
svxb.cn
flwx.cn
uav.sn.cn
w81.net
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
サーチエンジンプログラム
广州订购月饼
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。