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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM