如何在android中设置Authorization标头来调用rest api?

时间:2016-04-26 04:27:57

标签: php android json rest

我在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();
        }
    }

这是我在php中的 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应用程序添加任务?

4 个答案:

答案 0 :(得分:1)

您可以使用:

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

另外,您可以参考this文档了解更多信息。

答案 1 :(得分:1)

按如下方式使用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");

答案 2 :(得分:0)

你可以尝试这样......

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;
}

答案 3 :(得分:0)

使用URLConnection

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