PHP发送GET和POST请求

发送GET请求

 1 $url = "http://xxx.xxx.xxx.xxx";
 2 $get_data = array ("output" => "json",
 3                 "a" => "xxx",
 4                 "b" => "xxx",
 5                 "ak" => $ak,
 6                 "origins" => $origins, 
 7                 "destinations" => $destinations
 8                 );
 9 
10 foreach ($get_data as $k => $v) {
11      $data[] = $k.'='.$v;
12 }
13 $p_str = implode('&', $data);
14 $url .= '?'.$p_str;
15 
16 $ch = curl_init();
17 
18 curl_setopt($ch, CURLOPT_URL, $url);
19 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
20 
21 $output = curl_exec($ch);
22 curl_close($ch);
23 
24 $output_array = json_decode($output,true);

步骤:

1、先拼出url

2、使用curl一系列函数

3、得到结果之后使用json_decode函数进行json的解析,可以直接通过k-v的形式拿到值

 

发送POST请求

 1 $url = "xxx.xxx.xxx.xxx";
 2 
 3 $pieces1 = explode(",", $origins);
 4 $pieces2 = explode(",", $destinations);
 5 
 6 $params = json_encode(array
 7     (
 8     'xxx_list' => array
 9         (
10             array(
11                 'xx1' => array(
12                     'a' =>  intval($pieces1[0]),
13                     'b' =>  intval($pieces1[1]) 
14                 ),
15                 'xx2' => array(
16                     'c' =>  intval($pieces2[0]),
17                     'd' =>  intval($pieces2[1])
18                 ),
19                 'xx3' => array(
20                     'xx11' => $data['xx11'],
21                     'xx22' => $data['xx22']
22                 )
23             )
24         ),
25         'xxx_type' => 0
26     )
27 );
28 
29 
30 $ch = curl_init();
31 
32 curl_setopt($ch, CURLOPT_URL, $url);
33 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
34     'Content-Type: application/json',
35     'Content-Length: ' . strlen($params)
36 ));
37 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
38 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
39 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
40 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
41 
42 $res = curl_exec($ch);
43 curl_close($ch);

步骤:

1、构造params

2、使用curl一系列函数

curl中CURLOPT_POSTFIELDS参数就是设置body的内容,这里设置为post提交是用CURLOPT_CUSTOMREQUEST而不是CURLOPT_POST,根据官网的说明:
CURLOPT_POST:启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
因为是要发送json格式,所以不能用这个。

 

 

本文参考自:

http://www.01happy.com/php-send-post-request-body-is-json/

http://www.01happy.com/php-post-request-get-json-param/

 

转载于:https://www.cnblogs.com/abc-begin/p/8135635.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值