Hello!

I am still learning how to program, and now I am writing a client on Android for a web resource. I understand how to organize the simplest authorization between an Android application and a php server. But I didn’t quite figure out how to make it so that I send username and password to the server, but I already received the token from the server and wrote it in shared preferences, for further authorization by the token. I understand how to give a token from the server, I’m wondering exactly how to accept a token on Android and write it to the repository for later authorization on it.

1 answer 1

I just made a project about this

Description of my asynchronous stream

import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import ru.diitcenter.labbaik.utils.DownloadListner; import ru.diitcenter.labbaik.utils.ApplicationContext; import ru.diitcenter.labbaik.internet.base.Make; import ru.diitcenter.labbaik.internet.base.ReturnTypeData; import ru.diitcenter.labbaik.utils.CommonUtilities; public class StreamAuth extends AsyncTask<Void, Void, ReturnTypeData> { private String name_familia; private String date; private String pass; private DownloadListner listner; ReturnTypeData itemResult; public StreamAuth(DownloadListner listner, String name_familia, String date, String pass) { // интерфейс this.listner = listner; try { this.name_familia = URLEncoder.encode(name_familia, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } this.date = date; this.pass = pass; } @Override protected ReturnTypeData doInBackground(Void... params) { if (pass.equals("")){ itemResult = new Make().getJsonObject("GET", CommonUtilities.URL_AUTHOR1+"?fio=" + name_familia + "&date=" + date, null, CommonUtilities.TAG_AUTHOR1); if (itemResult.innerError == 0 && itemResult.error == 0) { try { JSONObject object = itemResult.jsonObject; SharedPreferences sPref = ApplicationContext.getAppContext().getSharedPreferences("SavedIdToken", Context.MODE_PRIVATE); SharedPreferences.Editor ed = sPref.edit(); ed.putLong("id", Long.parseLong(object.getString("id"))); ed.putString("token", object.getString("token")); ed.apply(); } catch (JSONException e) { e.printStackTrace(); Log.e(CommonUtilities.TAG_AUTHOR1, "ошибка парсинга- фио и дата"); } } } else{ //Log.e("StreamAuth.pass",""+pass); itemResult = new Make().getJsonObject("GET", CommonUtilities.URL_AUTHOR2+"?fio=" + name_familia + "&pass=" + pass, null, CommonUtilities.TAG_AUTHOR1); if (itemResult.innerError == 0 && itemResult.error == 0) { try { JSONObject object = itemResult.jsonObject; SharedPreferences sPref = ApplicationContext.getAppContext().getSharedPreferences("SavedIdToken", Context.MODE_PRIVATE); SharedPreferences.Editor ed = sPref.edit(); ed.putLong("id", Long.parseLong(object.getString("id"))); ed.putString("token", object.getString("token")); ed.apply(); } catch (JSONException e) { e.printStackTrace(); Log.e(CommonUtilities.TAG_AUTHOR1, "ошибка парсинга - фио и пароль"); } } } return itemResult; } @Override protected void onPostExecute(ReturnTypeData item) { super.onPostExecute(item); if (listner == null) { return; } if (item.innerError != 0) { Toast.makeText(ApplicationContext.getAppContext(), item.innerErrorInfo, Toast.LENGTH_SHORT).show(); listner.downloadFinish(false); } if (item.error != 0) { Toast.makeText(ApplicationContext.getAppContext(), item.error_info, Toast.LENGTH_SHORT).show(); listner.downloadFinish(false); } else { listner.downloadFinish(true); } } } 

And here's how to write in Preferences

  SharedPreferences sPref = ApplicationContext.getAppContext().getSharedPreferences("SavedGPSlocation", Context.MODE_PRIVATE); // ApplicationContext.getAppContext() - мой класс, я просто вытаскиваю context программы // SavedGPSlocation - название файла преференса. При работе с преференсом выбирай нужный. //Context.MODE_PRIVATE или просто MODE_PRIVATE - это тип доступа. Тебе должен подойти этот SharedPreferences.Editor ed = sPref.edit(); // настройка на редактирование ed.putString("znachenie1", znachenie1);//внести в поле "znachenie1" своё значение ed.putString("znachenie2", znachenie2); ed.putString("action", action); ed.putInt("server", 0); // внести 0 в строку сервера ed.apply(); //принять 

And here is how to read

 SharedPreferences sharedPreferences = getSharedPreferences("SavedIdToken", MODE_PRIVATE); long id = sharedPreferences.getLong("id", 0); String token = sharedPreferences.getString("token", ""); 

Where: getLong ("id", 0) - this is to pull out the value of the field or to pull out 0 by default

getString ("token", "") - in the string, by default, I get void

If something is not clear, ask in the comments, I will be glad to help

  • Thank you very much, I have already thought of how to do everything, but still I am glad that we have responded. - Alexander Shibaev
  • @ Alexander Shibaev, please) - zayn1991