使用curl发起get、put请求

在PHP中使用curl命令对接口发送请求,获取信息。

在发送发送请求时势必需要带一些信息。

如在header中带Authorization认证信息,

在row中带json格式等格式的信息。

如下示例中,put和get的请求演示了如何写header和json

1.put请求

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

     

     * @method put

     * @access protected

     */

    public function get() {

        $url 'https://XXXXXX';

        $arr=array('subject'=>'123');

        $data_string = json_encode(array('ticket'=> $arr));

        $ch = curl_init(); //初始化CURL句柄

        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(

            'Content-Type: application/json; charset=utf-8',

            "Authorization: BasxKa2NzMjAyMjExOnFsY3Noal8yNTg5")

            );  //设置请求头

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);//设置提交的字符串

   

        $output = curl_exec($ch);

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        throw new HttpResponseException(json(['code'=>$return_code'result'=>$output,'arr'=>$data_string]));

    }

对应python的代码为

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

def demo_put():

    url = 'XXXX'

    json = {

        "ticket": {

            "subject""测试0011"

        }

    }

    headers = {

        "Authorization""BasKa2NzMjAyMjExOnFsY3Noal8yNTg5",

        "Content-Type""application/json"

    }

    res = requests.put(url=url, json=json, headers=headers)

    print(res.status_code)

    print(res.json())

2.get请求

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public function getinfo() {

        $url 'XXXXX';

        $ch = curl_init($url);

         

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, array(

            'Content-Type: application/json; charset=utf-8',

            "Authorization: BasxKa2NzMjAyMjExOnFsY3Noal8yNTg5"));

        // 执行 并把执行后的数据赋值给 $data

        $data = curl_exec($ch);

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭

        curl_close($ch);

        // dump(json_decode($data));

        throw new HttpResponseException(json(['code'=>$return_code'result'=>json_decode($data)]));

    }

对应python的代码为

def demo_get():

    url = 'XXXX'

    headers = {

        "Authorization""BasiKa2NzMjAyMjExOnFsY3Noal8yNTg5",

        "Content-Type""application/json"

    }

    res = requests.get(url=url, headers=headers)

    print(res.status_code)

    pprint.pprint(res.json())

上述两种示例中通过CURLOPT_HTTPHEADER,定义头信息。

通过CURLOPT_POSTFIELDS方式定义json信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值