webguosai/http-client

v2.2.4 2023-06-12 03:59 UTC

This package is auto-updated.

Last update: 2024-04-12 05:39:20 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

运行环境

  • php >= 5.6
  • composer

安装

composer require webguosai/http-client -vvv

使用

初始化

$options = [
    //超时(单位秒)
    'timeout'     => 3,

    //代理ip池(允许填写多个,会随机使用一组)
    'useSocks5'   => true, // 使用 socks5 代理
    'proxyIps'    => [
        //格式为【ip:端口】
        '0.0.0.0:8888'
    ],

    //重定向、及最多重定向跳转次数
    'redirects'   => false,
    'maxRedirect' => 5,
    
    //cookie自动保存路径
    'cookieJarFile' => 'cookie.txt',

    //ca证书路径
    'caFile'        => __DIR__.'/cacert/cacert.pem',
];
$http = new \Webguosai\HttpClient($options);

请求

$headers = [
    'User-Agent' => 'http-client browser',
    'cookie' => 'login=true'
];
$data = ['data' => '111', 'data2' => '222'];

//所有方法
$response = $http->get($url, $data, $headers);
$response = $http->post($url, $data, $headers);
$response = $http->put($url, $data, $headers);
$response = $http->patch($url, $data, $headers);
$response = $http->delete($url, $data, $headers);
$response = $http->head($url, $data, $headers);
$response = $http->options($url, $data, $headers);

响应

$response->request; //请求
$response->headers; //响应头
$response->body; //响应body
$response->httpStatus; //http状态码
$response->contentType; //内容类型
$response->info; //其它信息
$response->info['url'];//最终请求的地址
$response->getHtml(); //获取html
$response->getChatset(); //编码
$response->json(); //json
$response->xml(); //xml
$response->ok();//http=200返回真
$response->getErrorMsg(); //错误信息

data 传值方式

// multipart/form-data
$data = ['data' => '111', 'data2' => '222'];

// application/x-www-form-urlencoded
$data = http_build_query($data); 

// application/json
$data = json_encode($data); 

// 文件上传 $_FILES['file'] 接收
$data = [
    'file' => new \CURLFile('1.jpg'),
];

$response = $http->post($url, $data);

headers 传值方式

//数组传递 
$headers = [
    'User-Agent: chrome',
    'User-Agent' => 'chrome',
];

//纯字符串 (一般为从浏览器复制)
$headers = 'User-Agent: chrome
Referer: https://www.x.com
Cookie: cookie=6666666';

$response = $http->post($url, $data, $headers);

实操

$options = [
    'timeout'   => 3,
];
$http    = new \Webguosai\HttpClient($options);
$response = $http->get('http://www.baidu.com');
if ($response->ok()) {
    var_dump($response->body);
    //var_dump($response->json());
} else {
    var_dump($response->getErrorMsg());
}

打赏

68747470733a2f2f7778342e73696e61696d672e636e2f6d77313032342f303038766f44783367793168366c31617a707779736a333075303134777439682e6a7067 68747470733a2f2f7778322e73696e61696d672e636e2f6d77313032342f303038766f44783367793168366c31617a703576686a3330753031616f6164632e6a7067

License

MIT