yii2 中 linslin\Curl的基本使用
一、get请求:
1.1 简单get请求
use linslin\yii2\curl; $curl = new curl\Curl(); //get http://example.com/ get请求改网址 $response = $curl->get('http://example.com/'); // curl对象有errorCode和errorerrorText 属性,分别为错误代码和错误说明 if ($curl->errorCode === null) { echo $response; } else { // 可以从这里获得所有的错误代码 https://curl.haxx.se/libcurl/c/libcurl-errors.html switch ($curl->errorCode) { case 6: //host unknown example break; } }
1.2、get 发起请求并且携带参数
GET request with GET params
// GET request with GET params // get 发起请求并且携带参数 // 例如 http://example.com/?key=value&scondKey=secondValue $curl = new curl\Curl(); $response = $curl->setGetParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->get('http://example.com/');
二、POST请求
2.1、post 请求 , 数据格式为 form-urlencoded格式
// POST URL form-urlencoded // post 请求 , 数据格式为 form-urlencoded格式 $curl = new curl\Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->post('http://example.com/');
2.2、发起post请求,数据为json格式
POST RAW JSON
// POST RAW JSON // 发起post请求,数据为json格式 $curl = new curl\Curl(); $response = $curl->setRawPostData( json_encode([ 'key' => 'value', 'secondKey' => 'secondValue' ])) ->post('http://example.com/');
2.3、POST RAW XML发起post请求
数据为xml格式
// POST RAW XML // 发起post请求,数据为xml格式 $curl = new curl\Curl(); $response = $curl->setRawPostData('<?xml version="1.0" encoding="UTF-8"?><someNode>Test</someNode>') ->post('http://example.com/');
2.4、设置header头部参数
// POST with special headers // 发起post请求,并且设置header头部参数 $curl = new curl\Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->setHeaders([ 'Custom-Header' => 'user-b' ]) ->post('http://example.com/');
2.5、发起post请求,数据作为body以json串来传递,并且设置header头部参数
// POST JSON with body string & special headers // 发起post请求,数据作为body以json串来传递,并且设置header头部参数 $curl = new curl\Curl(); $params = [ 'key' => 'value', 'secondKey' => 'secondValue' ]; $response = $curl->setRequestBody(json_encode($params)) ->setHeaders([ 'Content-Type' => 'application/json', 'Content-Length' => strlen(json_encode($params)) ]) ->post('http://example.com/');
2.6、Avanced POST request with curl options & error handling
// Avanced POST request with curl options & error handling post请求,设置参数 $curl = new curl\Curl(); $params = [ 'key' => 'value', 'secondKey' => 'secondValue' ]; $response = $curl->setRequestBody(json_encode($params)) ->setOption(CURLOPT_ENCODING, 'gzip') ->post('http://example.com/'); // List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes switch ($curl->responseCode) { case 'timeout': //timeout error logic here break; case 200: //success logic here break; case 404: //404 Error logic here break; } //list response headers var_dump($curl->responseHeaders);