我在之前的文章中介紹了 WordPress 提供用於發送 Http 請求的 WP_Http 類,但在實際使用過程中一般不需要直接調用類,而是使用 WordPress 幫我們封裝好的函數,可以讓代碼變的更加簡潔。
發送 GET 請求
發送普通的 GET 請求直接用 wp_remote_get() 函數,下邊是一個簡單的例子:
|
1 |
$response=wp_remote_get('http://www.weixiaoduo.com'); |
如果要添加 GET 參數的話可以直接在請求的鏈接後邊添加查詢字符串,或者使用 add_query_arg() 函數生成:
|
$response=wp_remote_get(add_query_arg('wd','搜索關鍵詞','http://www.baidu.com/s')); //添加多個參數 $response=wp_remote_get(add_query_arg(array( 'wd'=>'搜索關鍵詞', 'ie'=>'utf-8' ),'http://www.baidu.com/s')); |
發送 POST 請求
發送 POST 請求使用 wp_remote_post() 函數,例子:
|
//查詢參數 $args=array( 'name'=>'斌果', 'blog_url'=>'http://www.bgbk.org' ); //發送請求 $response=wp_remote_post('http://www.weixiaoduo.com',array('body'=>$args)); |
解析請求結果
在上邊的例子中,我都把請求的結果保存在了 $response 變量裏,這個參數裏包含所有請求的信息,那該如何從這個變量中找到我們要的信息呢?需要使用幾個函數:
- wp_remote_retrieve_response_code():獲取請求的 Http 狀態碼,請求成功則返回 200
- wp_remote_retrieve_body():獲取請求的內容
- wp_remote_retrieve_response_message():獲取請求結果的信息
- wp_remote_retrieve_header():獲取請求結果的頭信息
另外值得一提的是,如果請求發生異常,會返回一個 WP_Error,裏邊包含錯誤信息。
下邊是一個完整的請求:
|
//查詢參數 $args=array( 'name'=>'斌果', 'blog_url'=>'http://www.bgbk.org' ); //發送請求 $response=wp_remote_post('https://www.weixiaoduo.com/adfad',array('body'=>$args)); //判斷請求是否成功 if(is_wp_error($response)||wp_remote_retrieve_response_code($response)!==200)die('請求錯誤'); //獲取請求內容 $result=wp_remote_retrieve_body($response); |
如果你想獲取請求的 header 頭信息,可以參考下邊,下邊的例子獲取了 header 頭中的服務器信息:
|
1 |
$server=wp_remote_retrieve_header($response,'server'); |