dth20986 2017-02-24 13:46
浏览 53

通过android验证rest api(PHP)的会话

I have created a rest API which is handling a session. I want to validate that session through android.

MY ANDROID CODE FOR ACCESS API

        URL url = new URL("xxx.xxx.x.x./dir/file_name.php");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        DataOutputStream streamWriter = new   DataOutputStream(connection.getOutputStream());
        streamWriter.write(parameters.getBytes());
        streamWriter.flush();
        streamWriter.close();

        InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
        BufferedReader br = new BufferedReader(streamReader);
        String line;
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        webResult= sb.toString();
        return webResult;

MY PHP side code for checking that Session (it is perfectly working in browser)

// start PHP tag here

$sessionID = "something " ;

session_start();

if ( ! isset( $_SESSION['Id'] ) || $sessionID != $_SESSION['Id'] ) {

echo "Invalid session";
die();

} else {

echo "Session is active.";

}

// close PHP tag here

  • 写回答

1条回答 默认 最新

  • dongpao9165 2017-02-24 14:19
    关注

    I am not sure you can use sessions with Android. The idea of a session is that you use the cookies of the browser to store a session ID, and I think Android Apps don't allow cookies.

    However, what you can do is something similar:

    1. You generate a random string in PHP

    You can use This function to generate the random string.

    2. Store it somewhere in your database with an expiration time

    Basically, if you want a session to last for 1 hour, you store an expiration time equal now + 1 hour.

    3. Send it to the App and store it somewhere in the app

    So now, you how a random string which is the session ID. It is stored on the App side, and on the server side.

    Now anytime you want to store a session variable, you retrieve the session ID (you send it from the app, then check if it exists on the server side). Then you store the variable in your database with the following attributes: Session_id, var_name, var_value.

    Then, when you want to retrieve a session variable, you can do it through the session_id and var_name.

    Then, basically, if the session_id has expired (current date > expiration date), you remove all the variables with this session id, and generate a new empty one.

    Hope this helps :-)

    评论

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题