首页 > 解决方案 > 将从 api 获得的令牌保存到内部存储

问题描述

我创建了一个从 API 获取令牌的工作登录表单。现在我想将该令牌保存在我的内部存储中。有一些功能可以使用,但问题是我在 try 中获取我的 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);
    }
}} 

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

标签: androidjsonapi

解决方案


您可以使用 SharedPreferences 相同的:

// 创建一个保存token的方法

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

推荐阅读