douzha5990
douzha5990
2015-10-28 18:07
浏览 90

使用android-query时在php服务器上丢失会话

I have a problem in use AndroidQuery ajax method ...

here is my php code on server for page1.php :

<?php
session_start();
$_SESSION["valid_user"] = "mysession";
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>

and below php code on server for page2.php :

<?php
session_start();
echo '{ "value" : "S_'.$_SESSION["valid_user"].'" }' ;
?>

so then , on android , under image is my app screen :

http://i.stack.imgur.com/4esSo.png

event for "run page 1" button is :

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
        }
    });

and event for "run page 2" button is :

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_
        }
    });

first I click on "run page 1" button and then show "S_mysession" , so next I click on "run page 2" button and then show "S_" !!! , why loss my session in other connection by AQuery.ajax ?! please help me ...

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhi4498
    dongzhi4498 2016-05-09 07:30
    已采纳

    im using org.apache.httpcomponents plugin , and it work ! just add here codes to build.gradle file :

    compile 'org.apache.httpcomponents:httpcore:4.4.4'
    compile 'org.apache.httpcomponents:httpmime:4.3.5'
    

    so use under 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();
        }
    }
    }
    
    点赞 评论

相关推荐