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


how to manage PHP session in android using 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为方法设置了PHPSSID Cookie,我也尝试了这里的答案中的方法如何在HttpClient 4.1中处理会话,但它不起作用。我可以登录,当在CookieSotre中打印Cookie时,我可以看到PHPSSID已设置,但服务器也不能认为我已登录。。这是我的代码
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,还有其他的头吗?请帮忙。。

我对HTTP组件了解不多,但有一个不错的网页可以帮助你:HttpComponents Wiki

此外,:

  1. 与其简单地启动PHP会话,不如尝试

session_id()

在第一个片段中。

  1. 检查Java的缓存是否已激活。尝试标记属性

  2. URLConnect读取cookie

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

祝你好运!!!