使用 android-query 时在 php 服务器上丢失会话
loss session on php server when using android-query
我在使用 AndroidQuery ajax 方法时遇到问题...
这是我在服务器上的 php 代码 page1.php :
<?php
session_start();
$_SESSION["valid_user"] = "mysession";
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>
服务器上 及以下 php 代码 page2.php :
<?php
session_start();
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>
那么,在 android 上,图像下方是我的应用程序屏幕:
http://i.stack.imgur.com/4esSo.png
"run page 1" 按钮的事件是:
aQuery.ajax("http://www.example.com/page1.php", JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Toast.makeText(aQuery.getContext(), json.getString("valid_user"), Toast.LENGTH_LONG).show(); // print : S_mysession
}
});
"run page 2" 按钮的事件是:
aQuery.ajax("http://www.example.com/page2.php", JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Toast.makeText(aQuery.getContext(), json.getString("valid_user"), Toast.LENGTH_LONG).show(); // print : S_
}
});
首先我点击 "run page 1" 按钮然后显示 "S_mysession" ,接下来我点击 "run page 2" 按钮然后显示 "S_" !!! ,为什么 AQuery.ajax 在其他连接中丢失我的会话?!
请帮助我...
我正在使用 org.apache.httpcomponents 插件,而且它有效!
只需将这里的代码添加到 build.gradle 文件:
compile 'org.apache.httpcomponents:httpcore:4.4.4'
compile 'org.apache.httpcomponents:httpmime:4.3.5'
所以在class下使用:
/* saleh mosleh , www.smprogram.com */
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
interface CallBackAjax {
void success(JSONObject json);
}
public class Ajax {
private Context that;
public static HttpClient httpclient = null;
public Ajax(Context t){
that = t;
if(httpclient == null) {
httpclient = new DefaultHttpClient();
}
}
public HttpGet _httpget;
private String GET(String url){
InputStream inputStream = null;
String result = "";
try {
_httpget = new HttpGet(url);
_httpget.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse httpResponse = httpclient.execute(_httpget);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String POST(String url ,List<NameValuePair> nameValuePair){
InputStream inputStream = null;
String result = "";
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String POSTbyFile(String url ,List<NameValuePair> nameValuePair){
String result = "";
InputStream inputStream = null;
try {
HttpPost httpPost = new HttpPost(url);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePair.size(); index++) {
if(nameValuePair.get(index).getName().equalsIgnoreCase("file")) {
File file = new File(nameValuePair.get(index).getValue());
FileBody fb = new FileBody(file);
entityBuilder.addPart(nameValuePair.get(index).getName(), fb);
} else {
entityBuilder.addTextBody(nameValuePair.get(index).getName(), nameValuePair.get(index).getValue());
}
}
HttpEntity entity = entityBuilder.setBoundary(boundary).build();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) that.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
public List<NameValuePair> nameValuePair;
@Override
protected String doInBackground(String... urls) {
return POST(urls[0], nameValuePair);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
private class HttpPostFileAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
public List<NameValuePair> nameValuePair;
@Override
protected String doInBackground(String... urls) {
return POSTbyFile(urls[0], nameValuePair);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
public void get(String url ,CallBackAjax callback){
try {
if(isConnected()) {
HttpGetAsyncTask async = new HttpGetAsyncTask();
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void post(String url , List<NameValuePair> params ,CallBackAjax callback){
try {
if(isConnected()) {
HttpPostAsyncTask async = new HttpPostAsyncTask();
async.nameValuePair = params;
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void postbyfile(String url , List<NameValuePair> params ,CallBackAjax callback){
try {
if(isConnected()) {
HttpPostFileAsyncTask async = new HttpPostFileAsyncTask();
async.nameValuePair = params;
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
我在使用 AndroidQuery ajax 方法时遇到问题...
这是我在服务器上的 php 代码 page1.php :
<?php
session_start();
$_SESSION["valid_user"] = "mysession";
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>
服务器上 及以下 php 代码 page2.php :
<?php
session_start();
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>
那么,在 android 上,图像下方是我的应用程序屏幕:
http://i.stack.imgur.com/4esSo.png
"run page 1" 按钮的事件是:
aQuery.ajax("http://www.example.com/page1.php", JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Toast.makeText(aQuery.getContext(), json.getString("valid_user"), Toast.LENGTH_LONG).show(); // print : S_mysession
}
});
"run page 2" 按钮的事件是:
aQuery.ajax("http://www.example.com/page2.php", JSONObject.class, new AjaxCallback<JSONObject>() {
@Override
public void callback(String url, JSONObject json, AjaxStatus status) {
Toast.makeText(aQuery.getContext(), json.getString("valid_user"), Toast.LENGTH_LONG).show(); // print : S_
}
});
首先我点击 "run page 1" 按钮然后显示 "S_mysession" ,接下来我点击 "run page 2" 按钮然后显示 "S_" !!! ,为什么 AQuery.ajax 在其他连接中丢失我的会话?! 请帮助我...
我正在使用 org.apache.httpcomponents 插件,而且它有效! 只需将这里的代码添加到 build.gradle 文件:
compile 'org.apache.httpcomponents:httpcore:4.4.4'
compile 'org.apache.httpcomponents:httpmime:4.3.5'
所以在class下使用:
/* saleh mosleh , www.smprogram.com */
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
interface CallBackAjax {
void success(JSONObject json);
}
public class Ajax {
private Context that;
public static HttpClient httpclient = null;
public Ajax(Context t){
that = t;
if(httpclient == null) {
httpclient = new DefaultHttpClient();
}
}
public HttpGet _httpget;
private String GET(String url){
InputStream inputStream = null;
String result = "";
try {
_httpget = new HttpGet(url);
_httpget.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse httpResponse = httpclient.execute(_httpget);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String POST(String url ,List<NameValuePair> nameValuePair){
InputStream inputStream = null;
String result = "";
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String POSTbyFile(String url ,List<NameValuePair> nameValuePair){
String result = "";
InputStream inputStream = null;
try {
HttpPost httpPost = new HttpPost(url);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePair.size(); index++) {
if(nameValuePair.get(index).getName().equalsIgnoreCase("file")) {
File file = new File(nameValuePair.get(index).getValue());
FileBody fb = new FileBody(file);
entityBuilder.addPart(nameValuePair.get(index).getName(), fb);
} else {
entityBuilder.addTextBody(nameValuePair.get(index).getName(), nameValuePair.get(index).getValue());
}
}
HttpEntity entity = entityBuilder.setBoundary(boundary).build();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) that.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
private class HttpPostAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
public List<NameValuePair> nameValuePair;
@Override
protected String doInBackground(String... urls) {
return POST(urls[0], nameValuePair);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
private class HttpPostFileAsyncTask extends AsyncTask<String, Void, String> {
public CallBackAjax callback;
public List<NameValuePair> nameValuePair;
@Override
protected String doInBackground(String... urls) {
return POSTbyFile(urls[0], nameValuePair);
}
@Override
protected void onPostExecute(String result) {
//Toast.makeText(that, result, Toast.LENGTH_LONG).show();
JSONObject json = null;
try {
json = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
callback.success(json);
}
}
public void get(String url ,CallBackAjax callback){
try {
if(isConnected()) {
HttpGetAsyncTask async = new HttpGetAsyncTask();
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void post(String url , List<NameValuePair> params ,CallBackAjax callback){
try {
if(isConnected()) {
HttpPostAsyncTask async = new HttpPostAsyncTask();
async.nameValuePair = params;
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
public void postbyfile(String url , List<NameValuePair> params ,CallBackAjax callback){
try {
if(isConnected()) {
HttpPostFileAsyncTask async = new HttpPostFileAsyncTask();
async.nameValuePair = params;
async.callback = callback;
async.execute(url);
}else{
callback.success(null);
}
}catch (Exception e){
e.printStackTrace();
}
}
}