在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信息。