1. 程式人生 > >【學習|總結】如何使用java和php傳送http請求

【學習|總結】如何使用java和php傳送http請求

第一篇部落格寫什麼呢=w=看看下面的吧

最近在學php後臺開發,遇到一個學號驗證問題,所以需要攜帶token請求學校介面返回學生資訊,通過解析json來獲取學生學號。這讓我想起大一下學期做java音樂播放器時也涉及到了請求介面的問題,下面來看一下具體實現吧~

  • java傳送請求並接收返回的json物件

工具包:

  1. httpClient相關包:在jdk中自帶直接import就好;
  2. json相關包:點這裡下載

java攜帶請求頭髮送http請求分為七步:

  1. 建立httpClient物件;
  2. 建立請求物件(get/post/delete),並設定請求的url;
  3. 往請求頭中加入一個鍵值對
  4. 用httpClient物件的execute()
    方法執行請求;
  5. 用HttpResponse的getEntity()方法獲取httpEntity物件,該物件包含了伺服器的響應內容。
  6. 關閉響應物件;
  7. 關閉httpClient。

具體參見如下程式碼(以GET為例):

package test.yubei.com.app.api;

import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.
impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; public class DoGet { /*執行GET請求 * *@param String api:要請求的url *@param String token:使用者token *@return JSONObject * */
public static JSONObject doGet(String api,String token){ try { //1、建立httpClient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); //2、建立get物件,設定url HttpGet get = new HttpGet(api); //3.往請求頭中加入一個鍵值對 get.setHeader("Authorization",token); //3、執行get請求 CloseableHttpResponse response = httpClient.execute(get); /* * HttpResponse的getEntity()方法可獲取HttpEntity物件, * 該物件包裝了伺服器的響應內容。程式可通過該物件獲取伺服器的響應內容。 */ String str = EntityUtils.toString(response.getEntity()); response.close(); //關閉響應物件 httpClient.close(); //關閉httpClient JSONObject jsonObject = new JSONObject(str); //將伺服器響應內容變成json物件 return jsonObject; } catch (JSONException | IOException e) { return null; } } }
  • PHP攜帶請求頭髮送請求並解析返回的json

cURL是一個利用URL語法在命令列下工作的檔案傳輸工具。cURL支援的通訊協議有FTP、FTPS、HTTP、HTTPS等。PHP可使用cURL庫快速傳送請求然後獲得伺服器響應內容,下面介紹幾個cURL常用函式:

  1. curl_init()

初始化cURL會話,返回 cURL 控制代碼,供curl_setopt()curl_exec()curl_close()函式使用。 2. curl_setopt ( resource $ch , string $option , mixed $value )

為 cURL 會話控制代碼設定選項,返回值為布林值。

這裡的$option引數是你想要的設定,$value是給這個$option指定的值。

官方文件中$optionint型別,但是經過實踐我認為是字串型別,所以修改為了string

這麼寫可能有點抽象還是寫不清楚這兩個引數是幹什麼的,舉個例子吧!

eg:$optionCURLOPT_RETURNTRANSFER的功能為設定傳輸方式,我想要直接輸出響應內容,於是我設定$value為0。我想要傳輸資料用別的變數來接它,於是我設定$value為1。

  1. curl_exec ( resource $ch )

執行給定的 cURL 會話。這個函式應該在初始化一個 cURL 會話並且設定完全部的選項後被呼叫。

  1. curl_close ( resource $ch )

關閉 cURL 會話並且釋放所有資源,返回值為空。cURL 控制代碼也會被刪除。

下面來看一個具體的例子吧:

<?php

    /*執行GET請求
     *
     *@param String $url:url
     *@return json
     */
    function doGet($url){
        //1、curl初始化
        $ch = curl_init();
        //2、設定URL
        curl_setopt($ch, CURLOPT_URL, $url);    
        //3、設定傳輸方式,引數為1表示傳輸資料,為0表示直接輸出顯示。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
        //4、設定請求頭
        curl_setopt($ch,CURLOPT_HTTPHEADER,array("Authorization:$token"));
        //5、執行請求
        $output = curl_exec($ch);
        if(empty($output)){
        	echo makeErrJson(50001,"Internal Server Error");
        }else{
        	$data = json_decode($output,true);
        	return $data;
        }
        //6、用完記得關掉
        curl_close($ch);
    }
    
    
    /*執行POST請求
     *
     *@param String $url:url
     *@return json
     */
    function doPost($url){
        //1、curl初始化
        $ch = curl_init();
        //2、設定URL
        curl_setopt($ch, CURLOPT_URL, $url);    
        //3、設定傳輸方式,引數為1表示傳輸資料,為0表示直接輸出顯示。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
        //4、設定post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //5、設定post資料
        $post_data = array(
            "stuno" => "17051804",
            "name" => "yubei"
        );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        //6、設定請求頭
        curl_setopt($ch,CURLOPT_HTTPHEADER,array("Authorization:$token"));
        //7、執行請求
        $output = curl_exec($ch);
        if(empty($output)){
        	echo makeErrJson(50001,"Internal Server Error");
        }else{
        	$data = json_decode($output,true);
        	return $data;
        }
        //8、用完記得關掉
        curl_close($ch);
    }
    
    
    /*生成錯誤資訊json
     *
     *@param String $code:錯誤程式碼
     *@param String $msg:錯誤資訊
     *@return json
     */
    function makeErrJson($code,$msg){
		$json = array(
			"error" => $code,
			"msg" => $msg
		);
		return json_encode($json);
	}
	
?>