composer require cdcchen/curl-client:^1.0.0
$request = new HttpRequest();
$request->setUrl('http://www.baidu.com')
$response = $request->send();
返回的$response
类型为HttpResponse
。HttpResponse
会自动根据返回的Content-Type
解析返回的数据。目前支持以下格式:
- HttpRequest::FORMAT_JSON
- HttpRequest::FORMAT_XML
- HttpRequest::FORMAT_URLENCODED
- HttpRequest::FORMAT_RAW_URLENCODED
如果已经明确知道返回数据的格式,也可以显式的指定$response
的format属性:
$response->setFormat(HttpRequest::FORMAT_JSON);
然后可以直接通过$response->getData()
来获取到解析之后的数据。
$response->getStatus()
$response->getContent();
$response->hasHeader($name);
$response->getHeader($name);
$response->getHeaders();
$response->getCookies();
$request->setConnectTimeout($value, $ms = false);
$request->setTimeout($value, $ms = false);
$request->setMethod('post');
$request->setData(array $data);
$request->setContent($content);
$request->addHeader($name, $value);
$request->addHeaders($headers);
$request->removeHeader($name);
$request->clearHeaders();
$request->setReferrer($referrer = true);
$request->setBasicAuth($username, $password);
$request->setUserPassword($username, $password);
$request->setUserAgent($agent);
$request->setFollowLocation($value = true, $maxRedirects = 5);
$request->setVersion($version);
$request->setAcceptEncoding($value);
$request->addCookie($name, $value);
$request->addCookies($cookies);
$request->setCookieFile($file, $jar = null);
$reqeust->setSSL($peer = false, $host = 2, array $extraOptions = []);
$request->addFile($input_name, $file, $mime_type = null, $post_name = null);
$request->addFiles($input_name, array $files, $mime_type = null, $post_name = null);
$request->clearFiles();
$file 可以为文件路径,也可以为CURLFile实例。
$request->setFormat($value);
request
会自动根据format的值来格式化data
format
的取值如下:
- HttpRequest::FORMAT_URLENCODED 默认
- HttpRequest::FORMAT_RAW_URLENCODED
- HttpRequest::FORMAT_JSON
- HttpRequest::FORMAT_XML
$request->addOption($name, $value);
$request->addOptions(array $options);
$request->removeOptions($options);
$request->clearOptions();
$request->resetOptions($setDefaultOptions = true);