Android 使用 okhttp 网络框架,实现登录功能,
Header请求头带 Token 账号密码以Json格式传给后台,
登录成功后保存 Token 本地保存账号密码
依赖:
dependencies { // okhttp implementation 'net.qiujuer.common:okhttp:3.0.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.4.2' // gson implementation 'com.google.code.gson:gson:2.8.2' //圆形图片依赖:(一般和glide一起用): implementation 'de.hdodenhof:circleimageview:2.2.0' //图片依赖比imagerloader更方便: implementation 'com.github.bumptech.glide:glide:3.7.0' }
主页面布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/img_android01" android:orientation="vertical" android:paddingHorizontal="12dp" tools:context=".LogonActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="150dp" android:hint="请输入手机号" android:padding="12dp" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:hint="请输入密码" android:padding="12dp" /> <!-- CheckBox--> <!-- android:buttonTint="#ffffff" CheckBox设置框子颜色--> <CheckBox android:id="@+id/logon_recall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:buttonTint="#ffffff" android:text="记住密码" /> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginHorizontal="30dp" android:layout_marginTop="24dp" android:background="#ffffff" android:text="登 录" android:textColor="#000000" /> <!-- <TextView--> <!-- android:id="@+id/login_zhuce"--> <!-- android:layout_width="wrap_content"--> <!-- android:layout_height="wrap_content"--> <!-- android:text="新用户注册" />--> </LinearLayout>
主页面:
package com.ksxy.ksxytake; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * 登录页面 */ public class LogonActivity extends AppCompatActivity { private String loginUrl = "http://192.168.3.243:8080/auth/login"; private EditText edit_name, edit_psd;//用户名和密码的文本输入框 private CheckBox checkBox;//是否保存密码的选择框 private Button btn;//登录按钮 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_logon); initView(); // 初始化数据 } /** * 初始化数据 */ private void initView() { checkBox = (CheckBox) findViewById(R.id.logon_recall); // 记住密码选择框 edit_name = (EditText) findViewById(R.id.name); edit_psd = (EditText) findViewById(R.id.password); btn = (Button) findViewById(R.id.btn_login); output(); // 刚进入就先取一次,看看当然状态 btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String mobile = edit_name.getText().toString().trim(); String password = edit_psd.getText().toString().trim(); // 输入框判空 if (mobile.isEmpty() || password.isEmpty()) { Toast.makeText(LogonActivity.this, "用户名/密码不能为空", Toast.LENGTH_SHORT).show(); } else { login(mobile, password); } } }); } /** * 登录 * * @param mobile * @param password */ private void login(String mobile, String password) { // 账号密码转为Json格式传给后台 MediaType JSON = MediaType.parse("application/json; charset=utf-8"); // 将要传的参数保存进Json对象 JSONObject jsJson = new JSONObject(); try { jsJson.put("username", mobile); jsJson.put("password", password); } catch (JSONException e) { e.printStackTrace(); } Log.d("111111 jsJson ====", ":" + jsJson); // 1 . 拿到OkHttpClient对象 OkHttpClient client = new OkHttpClient(); // 创建一个RequestBody(参数1:数据类型 参数2传递的json串) RequestBody requestBody = RequestBody.create(JSON, String.valueOf(jsJson)); // 3 . 构建Request,将FormBody作为Post方法的参数传入 Request request = new Request.Builder() .url(loginUrl) // .addHeader("Token", "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjQzM2Y3ZWE4LTZiMDctNGRjNy04ODYzLTE4OTgxNDgxOGY2NCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.rPkJDV85kZ44c7-WzH-1Ncsd2_WIQgfbh7QmUNJ6hH2DzKr4GZ6PICgLJhPzVbYdONy5xubsNv2QXLXcIaU4hg") .addHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjQzM2Y3ZWE4LTZiMDctNGRjNy04ODYzLTE4OTgxNDgxOGY2NCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.rPkJDV85kZ44c7-WzH-1Ncsd2_WIQgfbh7QmUNJ6hH2DzKr4GZ6PICgLJhPzVbYdONy5xubsNv2QXLXcIaU4hg") // .addHeader("Content-Type", "application/json;charset=UTF-8") .post(requestBody) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("111111 post 请求失败 ======", "e.getMessage()" + e.getMessage()); Log.d("111111 post 请求失败 ======", "e.request()" + call.request()); } @Override public void onResponse(Call call, Response response) throws IOException { // 请求成功返回结果 // 如果希望返回的是字符串 final String responseData = response.body().string(); // 如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件. InputStream responseStream = response.body().byteStream(); // 注意,此时的线程不是ui线程, // 如果此时我们要用返回的数据进行ui更新,操作控件,就要使用相关方法 Log.d("111111 post 请求成功 ===", "responseData >>" + responseData); Log.d("111111 post 请求成功 ===", "responseStream >>" + responseStream); runOnUiThread(new Runnable() { @Override public void run() { LogonBean bean = new Gson().fromJson(responseData, LogonBean.class); Log.d("111111post请求成功======", "getAccess_token" + bean.getData().getAccess_token()); // 存Token SharedPreferences sharedPreferences = getSharedPreferences("logonsp", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("token", bean.getData().getAccess_token()); editor.commit(); // // 取 Token // SharedPreferences sharedPreferences = getSharedPreferences("logonsp", MODE_PRIVATE); // Log.d("111111 MainActivity >>", "getAccess_token:" + sharedPreferences.getString("token", "")); input(); // Intent 去设置要跳转的页面 Intent intent = new Intent(LogonActivity.this, MainActivity.class); // 进行跳转 startActivity(intent); finish(); } }); } }); } /** * 取出缓存的账号密码 */ private void output() { // 第一个参数是文件名,第二个参数是模式(不明白可以去补习一下SharedPreferences的知识) SharedPreferences shared = getSharedPreferences("mypsd", MODE_PRIVATE); // 第一个参数就是关键字,第二个参数为默认值,意思是说如果没找到值就用默认值代替 String name1 = shared.getString("name", "");//同上,若没找到就让它为空"" String psd1 = shared.getString("psd", ""); boolean ischecked1 = shared.getBoolean("isChecked", false); edit_name.setText(name1); edit_psd.setText(psd1); checkBox.setChecked(ischecked1); } /** * 存到SD卡,判断选中获取缓存账号密码 */ private void input() { // 第一个参数是文件名,第二个参数是模式(不明白可以去补习一下SharedPreferences的知识) SharedPreferences.Editor edit = getSharedPreferences("mypsd", MODE_PRIVATE).edit(); // 判断选择框的状态 被选中isChecked或…… if (checkBox.isChecked()) { edit.putString("name", edit_name.getText().toString()); edit.putString("psd", edit_psd.getText().toString()); edit.putBoolean("isChecked", true); } else { // edit.clear(); // 若选择全部清除就保留这行代码,注释以下三行 edit.putString("name", edit_name.getText().toString());//只存用户名 edit.putString("psd", ""); edit.putBoolean("isChecked", false); } edit.commit(); } }
主页面Bean类:
package com.ksxy.ksxytake; public class LogonBean { /** * code : 200 * msg : null * data : {"access_token":"eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6Ijc1OGMwNDkxLTRhOTMtNGZlMS05MDkyLWVkY2ZiODc4NGFiZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.TltWdsgL2vj4zfLgMZqmnoxqzVtKIOdV12ECHdtsI0ODj5mi1kCF-hpjAHcybfU6761-P31DyBENV2OcCGY8NQ","expires_in":720} */ private int code; private Object msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getMsg() { return msg; } public void setMsg(Object msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * access_token : eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6Ijc1OGMwNDkxLTRhOTMtNGZlMS05MDkyLWVkY2ZiODc4NGFiZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.TltWdsgL2vj4zfLgMZqmnoxqzVtKIOdV12ECHdtsI0ODj5mi1kCF-hpjAHcybfU6761-P31DyBENV2OcCGY8NQ * expires_in : 720 */ private String access_token; private int expires_in; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } } }
。。。