Android令牌保存自json api

时间:2014-09-17 18:16:30

标签: android json sharedpreferences

我需要帮助从json对象数据存储acces_token和token_type,这样我可以让用户sesion工作, 每次用户登录时,都会对一个新令牌进行签名,我希望我的acctivity与令牌同步,当令牌终止(过期)时,用户返回登录,到目前为止我只通过“String _token_type”中的某个字符串进行sesion管理=“token_type”;“到目前为止,这是一个糟糕的结果,我还需要以某种方式将令牌和令牌类型发布到其他活动以通过用户令牌解析JsonObject,我真的很抱歉我的英语不好,也许是一个愚蠢的问题,我是真的很绝望,我试着弄清楚它3天

记录时

Json响应

code: 200
error: false
message: "Ok"
data: {
access_token: "585e35343139636330653062613965827"
expires_in: 86400
token_type: "Bearer"
}

代码

package baymd.baymdalpha;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import baymd.baymdalpha.librarys.JSONParser;


public class LoginActivity extends ActionBarActivity implements View.OnClickListener {



private static final String LOGIN_URL = "http://example.com/api/auth";
private static final String TAG_SUCCESS = "code";
private static final String TAG_MESSAGE = "message";
private static final String TAG_DATA="data";
private static final String TAG_TOKEN_TYPE="token_type";
private static final String TAG_TOKEN="access_token";
JSONArray data = null;
JSONParser jsonParser = new JSONParser();
private EditText user, pass;
private Button mSubmit;
private ProgressDialog pDialog;
private String token,token_type;


//Shared preff vars
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String _token = "access_token";
public static final String  _token_type= "token_type";
SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    user = (EditText) findViewById(R.id.inputEmail);
    pass = (EditText) findViewById(R.id.inputPass);


    mSubmit = (Button) findViewById(R.id.loginBtn);

    mSubmit.setOnClickListener(this);

    //Shared Prefs Thing


}
protected void onResume(){
    sharedpreferences=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    if(sharedpreferences.contains(_token)){

        Log.d("LOL",_token);

        if(sharedpreferences.contains(_token_type)){
            Intent i=new Intent(this,BayTab.class);
            startActivity(i);
        }
    }
    super.onResume();
}

@Override
public void onClick(View v) {
    new AttemptLogin().execute();


}

class AttemptLogin extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", username));
            params.add(new BasicNameValuePair("password", password));
            Log.d("request", "starting");

            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            success = json.getInt(TAG_SUCCESS);

            if (success == 200) {
                JSONObject c=json.getJSONObject(TAG_DATA);

               SharedPreferences.Editor editor=sharedpreferences.edit();

                token=c.getString(TAG_TOKEN);
                Log.d("TOKENS",token);
                 token_type=c.getString(TAG_TOKEN_TYPE);
                Log.d("TOKENS",token_type);

                String u = token;
                String p = token_type;
                editor.putString(_token,u);
                editor.putString(_token_type,p);
                Log.d("RESPONSEFROMSHARED.....",_token+" "+u+ "\n"+_token_type+" "+p);

                editor.commit();


                Log.d("Login Successeful", json.toString());
                Intent i = new Intent(LoginActivity.this, BayTab.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                json.getString(TAG_MESSAGE);
                return json.getString(TAG_MESSAGE);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;


    }

    @Override
    protected void onPostExecute(String s) {
        pDialog.dismiss();
        if (s != null) {

            Toast.makeText(LoginActivity.this, s, Toast.LENGTH_LONG).show();
        }
    }
}

}

1 个答案:

答案 0 :(得分:2)

您应该使用Google Gson。

首先创建两个模型类,一个用于Session Response,另一个用于数据对象。做如下: 1.创建模型。确保每个类都完全模仿响应键。另外,请确保每个类都有一个默认构造函数。

public class SessionResponse {

  int code;
  String error, message;
  Data data;

  public SessionResponse(){}

  public int getCode() {
      return code;
  }

  public void setCode(int code) {
      this.code = code;
  }

  public String getError() {
      return error;
  }

  public void setError(String error) {
      this.error = error;
  }

  public String getMessage() {
      return message;
  }

  public void setMessage(String message) {
      this.message = message;
  }

  public Data getData() {
      return data;
  }

  public void setData(Data data) {
      this.data = data;
  }
}

public class Data {

    String access_token, token_type;
    int expires_in;

    public Data(){}

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getToken_type() {
        return token_type;
    }

    public void setToken_type(String token_type) {
        this.token_type = token_type;
    }

    public int getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(int expires_in) {
        this.expires_in = expires_in;
    }

}

然后使用Google Gson支持库将Json转换为对象。然后,您可以将其存储到共享首选项,并从任何活动中获取它。或者甚至通过Intent将它传递给一个活动。

Gson gson = new Gson();

//get the class from JSON
SessionResponse response = gson.fromJson(jsonResponseString, SessionResponse.class);

//convert to String
String jsonResponse = gson.toJson(response);

我希望这是一个好的开始!