Curl

命名空间地址

EasySwoole\Core\Utility\Curl\Request

方法列表

初始化:

  • string url 请求地址
  1. function __construct(string $url = null)

设置请求地址:

  • string url 请求地址
  1. public function setUrl(string $url):Request

添加Cookie:

  • EasySwoole\Core\Utility\Curl\Cookie cookie
  1. public function addCookie(Cookie $cookie):EasySwoole\Core\Utility\Curl\Request

添加POST参数:

  • EasySwoole\Core\Utility\Curl\Field field
  • bool isFile 是否为文件
  1. public function addPost(Field $field,$isFile = false):EasySwoole\Core\Utility\Curl\Request

添加GET参数:

  • EasySwoole\Core\Utility\Curl\Field field
  1. public function addGet(Field $field):EasySwoole\Core\Utility\Curl\Request

添加用户信息:

  • array opt 用户信息
  • bool isMerge 是否合并

如:opt 可以设置头部信息

  1. public function setUserOpt(array $opt,$isMerge = true):EasySwoole\Core\Utility\Curl\Request

执行请求:

  1. public function exec():EasySwoole\Core\Utility\Curl\Response

获得用户信息:

  1. public function getOpt():array

自定义封装示例

为了方便自己习惯再封装一下自己喜欢的套路,以下仅为示例代码:

  1. <?php
  2. namespace yourapp;
  3. use EasySwoole\Core\Utility\Curl\Response;
  4. use EasySwoole\Core\Utility\Curl\Request;
  5. use EasySwoole\Core\Utility\Curl\Field;
  6. class Curl
  7. {
  8. public function __construct()
  9. {
  10. }
  11. /**
  12. * @param string $method
  13. * @param string $url
  14. * @param array $params
  15. */
  16. public function request( string $method, string $url, array $params = null ) : Response
  17. {
  18. $request = new Request( $url );
  19. switch( $method ){
  20. case 'GET' :
  21. if( $params && isset( $params['query'] ) ){
  22. foreach( $params['query'] as $key => $value ){
  23. $request->addGet( new Field( $key, $value ) );
  24. }
  25. }
  26. break;
  27. case 'POST' :
  28. if( $params && isset( $params['form_params'] ) ){
  29. foreach( $params['form_params'] as $key => $value ){
  30. $request->addPost( new Field( $key, $value ) );
  31. }
  32. }elseif($params && isset( $params['body'] )){
  33. if(!isset($params['header']['Content-Type']) ){
  34. $params['header']['Content-Type'] = 'application/json; charset=utf-8';
  35. }
  36. $request->setUserOpt( [CURLOPT_POSTFIELDS => $params['body']] );
  37. }
  38. break;
  39. default:
  40. throw new \InvalidArgumentException( "method eroor" );
  41. break;
  42. }
  43. if( isset( $params['header'] ) && !empty( $params['header'] ) && is_array( $params['header'] ) ){
  44. foreach( $params['header'] as $key => $value ){
  45. $string = "{$key}:$value";
  46. $header[] = $string;
  47. }
  48. $request->setUserOpt( [CURLOPT_HTTPHEADER => $header] );
  49. }
  50. return $request->exec();
  51. }
  52. }

发起请求:

  1. <?php
  2. namespace yourapp;
  3. class Test{
  4. public function testRequest(){
  5. $response = $this->request( "POST", "http://www.easyswoole.com", [
  6. 'header' => ['Access-Token' = "xxxxxxxxxxxxxxxxxxxxxxx"],
  7. 'query' => ['keywords'=> '大吉大利 今晚吃鸡'],
  8. 'form_params' => ['title'=>'新添加一条记录','body'=>'文章内容']
  9. ] );
  10. }
  11. }