2015-10-28 4 views
0

У меня есть проблема в использование AndroidQuery метода АЯКС ...потеря сеанса на PHP-сервере при использовании андроида-запрос

вот мой 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

событие для "прогона страницы 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 
     } 
    }); 

и событие для "прогона страницы 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_ 
     } 
    }); 

первым я нажимаю на "запустить страницу 1" и затем отобразите «S_mysession», поэтому затем я нажимаю кнопку «запустить страницу 2», а затем показываю «S_» !!! , почему потеря моя сессия в другой связи AQuery.ajax?! , пожалуйста, помогите мне ...

ответ

0

im using org.apache.httpcomponents plugin, и он работает! просто добавьте сюда коды build.gradle файл:

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

так использовать под класс:

/* 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(); 
    } 
} 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^