首页 > 技术文章 > php以post方式向接口发送数据

zhaoshunjie 2016-09-22 15:16 原文

  工作需要,我负责收集服务器数据,然后定时向中心服务器发送。我看到了接口信息,需要设置heads头信息,需要发送数据,且是post方式。

 这里就用到了curl

 1    //发送post请求
 2     function request_post($url = '', $post_data = array()) {
 3         if (empty($url) || empty($post_data)) {
 4             return false;
 5         }  
 6         $o = "";
 7         foreach ( $post_data as $k => $v ) 
 8         { 
 9             $o.= "$k=" . urlencode( $v ). "&" ;
10         }
11         $post_data = substr($o,0,-1);
12         $postUrl = $url;
13         $curlPost = $post_data;
14         $headers = array(
15             'User-Agent:lalalla',
16             'TICKET:lllllllllllljjaajaj'
17         );
18         $ch = curl_init();//初始化curl
19         curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
20         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
21         curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
22         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
23         curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
24         curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
25         $data = curl_exec($ch);//运行curl
26         curl_close($ch);  
27         return $data;
28     }

其中我遇到了问题,就是我向对方发送,对方没有接到user-agent和ticket。这就肯定是这句的问题了

$headers = array(
            'User-Agent:ereree',
            'TICKET:sdfsdsf'
        );

或者下面这句的顺序问题(当时我是这样猜的)

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

后来发现我当初是这样写的

    $headers = array(
            'User-Agent' => 'ererere3',
            'TICKET'    => 'tttttttttttttttt'
        );

经常遇到curl,得学习一下里面的具体内容了

推荐阅读