【发布时间】:2015-11-29 20:31:49
【问题描述】:
我正在构建一个需要客户端登录才能返回一些信息的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
}
}
对于第二页,我使用了这个 sn-p 代码
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json");
HttpResponse response = ClientUtils.myHttpClient.execute(getRequest, ClientUtils.httpContext);
但这不起作用我总是得到错误的响应,我错过了什么吗?除了我应该使用的 sessionId 之外,还有其他标题吗? 请帮忙..
【问题讨论】:
标签: java php android cookies httpclient