【问题标题】:Why cookie is null?为什么 cookie 为空?
【发布时间】:2013-05-17 13:55:48
【问题描述】:

我用lamp(linux+apache+mysql+php)做了一个webserver。我想设置cookie来保存用户信息,比如userid,username。所以load.php是这样的:

....
///login successful
session_start(); 
$_COOKIE["userid"]=$userid;

$response["success"]=1;
$response["message"]="load successful";
echo json_encode($response); 
...

在 Android LoadActivity 中,我创建了一个扩展 AsyncTask 的类 WebLoader,并像这样覆盖函数 String doInBackground(String... params)

client=new DefaultHttpClient();
HttpPost post=new HttpPost(url_up);
...
HttpResponse response=client.execute(post);                 
HttpEntity entity=response.getEntity();
CookieStore mCookieStore = client.getCookieStore();
List<Cookie> cookies = mCookieStore.getCookies();
if(cookies.isEmpty())
   Log.d("cookie","cookie is none");
for (int i = 0; i < cookies.size(); i++) {
 if("userid".equals(cookies.get(i).getName()))
 {
        userid=Integer.parseInt(cookies.get(i).getValue());                 
  }
}

当我运行应用程序时,logcat 说:cookie is none。 为什么 Cookie 没有?我已经在 load.php 中设置了。

【问题讨论】:

    标签: android cookies httpclient


    【解决方案1】:

    您应该使用setcookie() 设置cookie。以您为例:

    setcookie("userid", $userid, time() + 60*60*24, "/");
    

    这将设置一个名为 userid 的 cookie,其值为 $userid,并将在设置后 31 天过期。

    【讨论】:

    • 对不起,cookie 也没有。
    • 您是否尝试过使用 HttpGet 而不是 HttpPost?你确定url_up 有效吗?我还添加了路径参数。你也可以试试吗?
    • 谢谢,终于发现是php脚本有问题,我没有正确改权限。当我用:sudo chmod 777 xxx.php 更改它时,一切正常!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多