如何使用HttpClient在android中管理PHP会话?

时间:2015-11-29 20:31:49

标签: java php android cookies httpclient

我正在构建一个需要登录客户端以返回一些信息的php API ..此页面的代码如下:

include('connect.php');
session_start();
if(isset($_SESSION['username'])) {
    # select data from the database and echo it back.
}
else {
    session_unset();
    session_destroy();
    echo -1;
}
?>

但在此之前,客户应该使用另一个页面登录`

if (isset($_GET['usr']) && isset($_GET['password'])){
    $usr = $_GET['usr'];
    $passwd = $_GET['password'];

    $login = 0;
    $stmt = $conn->prepare("select * from users where userName=? and passwd =?");
    $stmt->execute(array($usr,$passwd));
    while($row = $stmt->fetch()) {
            $login = 1;
            session_start();
            $id = session_id();
            $_SESSION['username'] = $usr;
            break;
    }

    if($login == 1) {       
        echo "signed on";
    }

    if($login == 0) {
        echo "username or password incorrect";
    }
}
else {
    echo "parameter not set";
}

?>

当我从浏览器中尝试这个时,效果非常好。但是当我从Android应用程序尝试这个似乎不起作用时,我使用setHeader为方法设置了PHPSESSID Cookie,我也尝试了这里的答案How to Handle the Session in HttpClient 4.1,但它没有用,我可以登录,当在CookieSotre中打印cookie时,我可以看到PHPSESSID已设置,但服务器也不能认为我已登录.. 这是我的代码
ClientUtils.java

public class ClientUtils {

public static final DefaultHttpClient myHttpClient = new DefaultHttpClient();
public static final HttpContext httpContext = new BasicHttpContext();
public static final CookieStore cookieStore = new BasicCookieStore();


public static void config() {
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

public static void printCookies() {
    for(Cookie k :cookieStore.getCookies())
        Log.d(k.getName(), k.getValue());
     }
}


LoginTask.java

public class LoginTask extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... url) {
    try {
        ClientUtils.config();
        String urlll = "http://192.168.200.15/login.php?usr=monim&password=monim";
        HttpGet httpget = new HttpGet(urlll);               
        HttpResponse response = ClientUtils.myHttpClient.execute(httpget, ClientUtils.httpContext); 
        ClientUtils.printCookies(); //this print the value of PHPSESSID
    }catch(Exception e) {}
    return null;
}
protected void onPostExecute(String... url) {
    // do something 
}
}


,对于第二页,我使用此代码段

HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", "application/json");
    HttpResponse response = ClientUtils.myHttpClient.execute(getRequest, ClientUtils.httpContext);

但这不起作用我总是得到错误的回答,我错过了什么吗?除了我应该使用的sessionId之外还有其他标题吗? 请帮忙..

1 个答案:

答案 0 :(得分:1)

我对HTTP Components的了解不多,但有一个很好的网页可以帮到你:HttpComponents Wiki

另外,:

  1. 您应该尝试获取
  2. ,而不是简单地启动PHP会话

    session_id()

    在第一个片段中。

    1. 检查是否已激活Java缓存。试试Tag Property

    2. URLConnection阅读Cookie

    3. this thread关于“如何在php应用程序和Java EE应用程序之间共享会话?”

    4. 祝你好运!!!