簡體   English   中英

如何在android中設置Authorization標頭來調用rest api?

[英]How to set Authorization header to call rest api in android?

我在xampp本地服務器上創建了一個測試休息API 我執行了一些任務,如用戶注冊,登錄用戶等。當用戶注冊時,為注冊用戶創建一個api_key 。當用戶嘗試執行添加任務時,我使用了一個驗證功能,獲取基於用戶的唯一ID在api_key上

這是我在php中的身份驗證功能:

function authenticate(\Slim\Route $route){
        //Getting request header
        $headers=apache_request_headers();
        $response=array();
        $app=\Slim\Slim::getInstance();


        //Verifying authorization Header

        if(isset($headers['Authorization'])){
            $db=new DbHandler();

            //Get api key
            $api_key=$headers['Authorization'];

            //validating api key

            if(!$db->isValidApiKey($api_key)){
                //Api key is not present in users table
                $response["error"]=TRUE;
                $response["message"]="Access_denied! Invalid api key";
                echoRespnse(401,$response);
                $app->stop();
            }
            else{
                global $student_id;

                //getUser primary key id

                $user=$db->getUserId($api_key);
                if($user!=NULL){
                    $student_id=$user['id'];
                }
            }
        }
        else{
            //api key is missing in header
            $response["error"]=TRUE;
            $response["message"]="Api key is missing";
            echoRespnse(400,$response);
            $api->stop();
        }
    }

這是IsValidApiKey()中的我的IsValidApiKey()函數。當我向本地服務器請求時,檢查api_key是否有效。

public function isValidApiKey($api_key) {
        $stmt = $this->conn->prepare("SELECT id from student WHERE api_key = ?");
        $stmt->bind_param("s", $api_key);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

以下是在我的db-table中添加任務的任務:

$app->post('/tasks','authenticate',function() use ($app){
        //Check for required params
        verifyRequiredParams(array('task'));

        $response=array();
        $task=$app->request->post('task');
        global $user_id;
        $db=new DbHandler();

        //Creating new task

        $task_id=$db->createTask($user_id,$task);

        if($task_id!=NULL){
            $response["error"]=FALSE;
            $response["message"]="Task created successfully";
            $response["task_id"]=$task_id;
        }
        else{
            $response["error"]=TRUE;
            $response["message"]="Failed to create a task. please, try again!!";

        }
        echoRespnse(201,$response);

    });

在上面的任務中,我使用了我的身份驗證功能。這意味着檢查這個api_key使用是否已經注冊,如果是,那么在我的任務表中添加任務,否則生成api密鑰丟失。

這是我的數據庫表

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `password_hash` text NOT NULL,
  `api_key` varchar(32) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
);

當我使用Advance API客戶端add-one執行此操作時,它可以工作,因為我在其標頭中傳遞了api_key。

我希望使用我的Android應用程序添加任務,如何在頭文件中添加api_key以便我可以使用android應用程序添加任務?

你可以用這個:

HttpPost post = new HttpPost( "your_api_url" );
post.addHeader( "Auth-Secret-Key" , "your_auth_secret_key" );

此外,您可以參考文檔以獲取更多信息。

使用HttpURlConnection如下:

URL myURL = new URL("yoururl");
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");//  change as your requested method
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");

你可以這樣試試......

public static JSONObject post(Context mContext, String REQUEST_URL,Map<String, Object> params) {
    JSONObject jsonObject = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(REQUEST_URL);
        StringBuilder postData = new StringBuilder();

        for (Map.Entry<String, Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("auth1", GPLUS_EmailID);
        connection.setRequestProperty("auth2", GPLUS_AccessToken);
        connection.setRequestProperty("auth4", GCM_token);
        connection.setConnectTimeout(8000);
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(8000);
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.getOutputStream().write(postDataBytes);
        connection.connect();
        StringBuilder sb;
        int statusCode = connection.getResponseCode();
        if (statusCode == 200) {
            sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            jsonObject = new JSONObject(sb.toString());
        }
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return jsonObject;
}

使用URLConnection

String credentials = username + ":" + password;
String basicAuth = "Basic " + new String(new Base64().encode(credentials.getBytes()));
myURLConnection.setRequestProperty ("Authorization", basicAuth);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM