【學習|總結】如何使用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()函數使用。

  1. 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);
	}
	
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章