如何保存会话标识符并在访问服务器时发送?

How to save the session identifier and send it when accessing the server?

要维护会话,我必须使用会话 ID。 如何保存会话标识符并在每次访问服务器时发送?

设置 Cookie:JSESSIONID=b09aa2c816d1b;

有人可以帮我解决这个问题吗??

要在本地设备中保存会话 ID,请使用共享首选项,这是用于保存和检索会话 ID 的共享首选项。



import android.content.Context;
import android.content.SharedPreferences;

public class SharedPrefManager {

    private static final String PREF_NAME = "AndroidHivePref";
    SharedPreferences pref;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;

    // Context
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 0;


    public SharedPrefManager(Context context){
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void savesession(String sessionid){
        editor.putString("SESSION_ID",session);
        editor.commit();
    }

   public String getsessionid(){
          String sessionid = pref.getString("SESSION_ID", null);
          return sessionid;
   }


}

用法


//To save Sessionid from onResponse method
...
@Override
    public void onResponse(Call<RegResponse> call, Response<RegResponse>response) {
          // Get sessionid from response object.

          ...
          SharedPrefManager manager = new SharedPrefManager(getApplicationContext());
           //Context object is require to create its object.

          ...
         manager.savesessionid(sessionid);//sessionid is string object got from response above

    }
  ....

// When you want to send sessionid to server either in request data or in request header, get sessionid string object from SharedPrefManager and append it to request object.


SharedPrefManager manager = new SharedPrefManager(getApplicationContext());

String sessionid = manager.getsessionid();