将从api获取的令牌保存到内部存储设备

时间:2018-07-18 10:49:03

标签: android json api

我创建了一个有效的登录表单,该表单从API获取令牌。现在我想将该令牌保存在我的内部存储中。有些功能可以使用,但问题是我正在尝试获取JSON数据。如果没有数据,则提示没有用户名密码(处于捕获状态)。

这是我的代码:0

public void signin_button(View v)
{
    Email = email.getText().toString();
    Password = password.getText().toString();
    BackGround b = new BackGround();
    b.execute(Email, Password);
}
class BackGround extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        String email = params[0];
        String password = params[1];
        String data="";
        int tmp;
        try {
            URL url = new URL("Website link can't show");
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("email", email));
            param.add(new BasicNameValuePair("password", password));
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(param));
            writer.flush();
            writer.close();
            os.close();
            conn.connect();
            InputStream is = conn.getInputStream();
            while((tmp=is.read())!=-1){
                data+= (char)tmp;
            }
            is.close();
            conn.disconnect();
            return data;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "Exception: "+e.getMessage();
        }
    }
    private String getQuery(List<NameValuePair> param) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (NameValuePair pair : param)
        {
            if (first)
                first = false;
            else
                result.append("&");
            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
        return result.toString();
    }

调用JSON的主要部分

 @Override
    protected void onPostExecute(String s) {
        String err=null;
        try {
            JSONObject root = new JSONObject(s);
            Token = root.getString("token");
        } catch (JSONException e) {
            e.printStackTrace();
            err = "Exception: "+e.getMessage();
        }
        Intent i = new Intent(ctx, LoginActivity2.class);
        i.putExtra("token", Token);
        i.putExtra("err", err);
        startActivity(i);
    }
}} 

我将如何将该部分保存到内部存储的任何帮助将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

您可以将SharedPreferences用于相同的内容:

//创建保存令牌的方法

private void saveString(Context context, String key, String text) {
        android.content.SharedPreferences settings;
        android.content.SharedPreferences.Editor editor;

        settings = context.getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
        editor = settings.edit();
        editor.putString(key, text);
        editor.apply();

///将您的令牌另存为

saveString(this, "TOKEN", Token);

//检索令牌方法

private String getString(Context context, String key) {
        android.content.SharedPreferences settings;
        String text;

        settings = context.getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
        text = settings.getString(key, null);
        return text;
    }

//以

检索令牌
String mToken = getString(this, "TOKEN);

答案 1 :(得分:0)

使用共享首选项

SaveData

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
editor.putString("token", "abcded");
editor.putInt("id", 12);
editor.apply();

读取数据

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String name = prefs.getString("token", "");
int idName = prefs.getInt("id", 0); //0 is the default value.