登录(记住账号密码、获取后台数据)

向右看齐 2023-08-17 17:09 192阅读 0赞

1、在build.gradle导入okHttp3

2、activity_mian.xml样式文件

3、创建保存账号密码类

4、主页代码

5、完成以上4个步骤后,部分手机上用不了(如果您使用的是http,Android9.0手机是用不了的,看本博客的“Android P不能使用http”解决不能使用http的方法)。

在build.gradle导入okHttp3(加入进去后记得在Android studio的右上角点击“Sync Now”同步)

  1. implementation 'com.squareup.okhttp3:okhttp:3.4.1' //okhttp3

activity_mian.xml样式文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. tools:context=".MainActivity">
  7. <ImageView
  8. android:id="@+id/iv"
  9. android:layout_width="70dp"
  10. android:layout_height="70dp"
  11. android:layout_centerHorizontal="true"
  12. android:layout_marginTop="40dp"
  13. android:background="@drawable/dongman"/>
  14. <LinearLayout
  15. android:id="@+id/ll_number"
  16. android:layout_width="match_parent"
  17. android:layout_height="wrap_content"
  18. android:layout_below="@+id/iv"
  19. android:layout_centerVertical="true"
  20. android:layout_marginTop="15dp"
  21. android:layout_marginLeft="10dp"
  22. android:layout_marginRight="10dp"
  23. android:layout_marginBottom="5dp"
  24. android:background="#ffffff">
  25. <TextView
  26. android:id="@+id/tv_number"
  27. android:layout_width="wrap_content"
  28. android:layout_height="wrap_content"
  29. android:padding="10dp"
  30. android:text="账号"
  31. android:textColor="#000"
  32. android:textSize="20sp"/>
  33. <EditText
  34. android:id="@+id/et_number"
  35. android:layout_width="match_parent"
  36. android:layout_height="wrap_content"
  37. android:layout_marginLeft="5dp"
  38. android:background="@null"
  39. android:padding="10dp"/>
  40. </LinearLayout>
  41. <LinearLayout
  42. android:id="@+id/ll_password"
  43. android:layout_width="match_parent"
  44. android:layout_height="wrap_content"
  45. android:layout_below="@+id/ll_number"
  46. android:layout_centerVertical="true"
  47. android:layout_marginTop="15dp"
  48. android:layout_marginLeft="10dp"
  49. android:layout_marginRight="10dp"
  50. android:layout_marginBottom="5dp"
  51. android:background="#ffffff">
  52. <TextView
  53. android:id="@+id/tv_password"
  54. android:layout_width="wrap_content"
  55. android:layout_height="wrap_content"
  56. android:padding="10dp"
  57. android:text="密码"
  58. android:textColor="#000"
  59. android:textSize="20sp"/>
  60. <EditText
  61. android:id="@+id/et_password"
  62. android:layout_width="match_parent"
  63. android:layout_height="wrap_content"
  64. android:layout_marginLeft="5dp"
  65. android:background="@null"
  66. android:padding="10dp"/>
  67. </LinearLayout>
  68. <Button
  69. android:id="@+id/btn_login"
  70. android:layout_width="match_parent"
  71. android:layout_height="wrap_content"
  72. android:layout_below="@+id/ll_password"
  73. android:layout_marginLeft="10dp"
  74. android:layout_marginRight="10dp"
  75. android:layout_marginTop="30dp"
  76. android:text="登录"
  77. android:background="#3C8DC4"
  78. android:textSize="20sp"/>
  79. </RelativeLayout>

创建保存账号密码类

  1. package com.example.remembernp;
  2. import android.content.Context;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class SaveFile {
  8. //把账号密码保存在data.txt文件中
  9. public static boolean saveUserInfo(Context context, String number, String password){
  10. try{
  11. FileOutputStream fos = context.openFileOutput("data.txt",Context.MODE_PRIVATE);
  12. fos.write((number + ":" + password).getBytes());
  13. fos.close();
  14. return true;
  15. }catch (Exception e){
  16. e.printStackTrace();
  17. return false;
  18. }
  19. }
  20. //从data.txt中去获取刚刚保存的账号密码
  21. public static Map<String,String> getUserInfo(Context context) {
  22. String content = "";
  23. try {
  24. FileInputStream fis = context.openFileInput("data.txt");
  25. byte[] buffer = new byte[fis.available()];
  26. fis.read(buffer);//读取
  27. content = new String(buffer);
  28. Map<String ,String > userMap = new HashMap<String, String>();
  29. String[] infos = content.split(":");
  30. userMap.put("number",infos[0]);
  31. userMap.put("password",infos[1]);
  32. fis.close();
  33. return userMap;
  34. }catch (Exception e){
  35. e.printStackTrace();
  36. return null;
  37. }
  38. }
  39. }

主页代码

  1. package com.example.remembernp;
  2. import androidx.appcompat.app.AppCompatActivity;
  3. import android.app.AlertDialog;
  4. import android.icu.util.LocaleData;
  5. import android.os.Bundle;
  6. import android.text.TextUtils;
  7. import android.util.Log;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.EditText;
  11. import android.widget.Toast;
  12. import org.json.JSONException;
  13. import org.json.JSONObject;
  14. import java.io.IOException;
  15. import java.io.UnsupportedEncodingException;
  16. import java.security.MessageDigest;
  17. import java.security.NoSuchAlgorithmException;
  18. import java.util.Map;
  19. import okhttp3.Call;
  20. import okhttp3.Callback;
  21. import okhttp3.MediaType;
  22. import okhttp3.OkHttpClient;
  23. import okhttp3.Request;
  24. import okhttp3.RequestBody;
  25. import okhttp3.Response;
  26. public class MainActivity extends AppCompatActivity implements View.OnClickListener{
  27. private EditText etNumber;
  28. private EditText etPassword;
  29. private Button btnLogin;
  30. private MediaType mediaType;
  31. @Override
  32. protected void onCreate(Bundle savedInstanceState) {
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.activity_main);
  35. Button btn = (Button)findViewById(R.id.btn_login);
  36. Map<String,String> userInfo = SaveFile.getUserInfo(this);
  37. initView();
  38. if(userInfo != null){
  39. etNumber.setText(userInfo.get("number"));
  40. etPassword.setText(userInfo.get("password"));
  41. }
  42. }
  43. private void initView(){
  44. etNumber = (EditText)findViewById(R.id.et_number);
  45. etPassword = (EditText)findViewById(R.id.et_password);
  46. btnLogin = (Button)findViewById(R.id.btn_login);
  47. btnLogin.setOnClickListener(this);
  48. }
  49. @Override
  50. public void onClick(View view) {
  51. //单击事件,获取账号密码
  52. final String number = etNumber.getText().toString().trim();
  53. String password = etPassword.getText().toString().trim();
  54. //检查账号密码是否正确
  55. if(TextUtils.isEmpty(number)){
  56. Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
  57. return;
  58. }
  59. if(TextUtils.isEmpty(password)){
  60. Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
  61. return;
  62. }
  63. okHttp(); //登录
  64. }
  65. private void okHttp(){
  66. //单击事件,获取账号密码
  67. final String number = etNumber.getText().toString().trim();
  68. final String password = etPassword.getText().toString().trim();
  69. //给密码加密
  70. final String md5 = md5Decode(password + "dabsdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,");
  71. new Thread(new Runnable() {
  72. @Override
  73. public void run() {
  74. try {
  75. OkHttpClient client = new OkHttpClient();
  76. JSONObject jsonObject = new JSONObject();
  77. jsonObject.put("number",number);
  78. jsonObject.put("password",md5);
  79. mediaType = MediaType.parse("application/json;charest=utf-8");
  80. RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
  81. final Request request = new Request.Builder() .url("使用自己的登录网址")
  82. .post(requestBody).build();
  83. client.newCall(request).enqueue(new Callback() {
  84. @Override
  85. //请求失败
  86. public void onFailure(Call call, IOException e) {
  87. Log.d("请求失败",",返回码:"+e.getMessage());
  88. loginRemind(400);
  89. }
  90. @Override
  91. //请求成功
  92. public void onResponse(Call call, final Response response) throws IOException {
  93. loginRemind(response.code());
  94. if(response.code() == 200){
  95. Log.d("请求成功---------","后台返回数据:"+response.body().string());
  96. //保存账号密码
  97. SaveFile.saveUserInfo(MainActivity.this,number,password);
  98. }else{
  99. Log.d("请求成功-----但登录失败----返回码:"+response.code(),"------失败原因:"+response.body().string());
  100. }
  101. }
  102. });
  103. } catch (JSONException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107. }).start();
  108. }
  109. public String md5Decode(String content) {
  110. byte[] hash;
  111. try {
  112. hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
  113. } catch (NoSuchAlgorithmException e) {
  114. throw new RuntimeException("NoSuchAlgorithmException", e);
  115. } catch (UnsupportedEncodingException e) {
  116. throw new RuntimeException("UnsupportedEncodingException", e);
  117. }
  118. //对生成的16字节数组进行补零操作
  119. StringBuilder hex = new StringBuilder(hash.length * 2);
  120. for (byte b : hash) {
  121. if ((b & 0xFF) < 0x10) {
  122. hex.append("0");
  123. }
  124. hex.append(Integer.toHexString(b & 0xFF));
  125. }
  126. return hex.toString();
  127. }
  128. private void loginRemind(final int num){
  129. MainActivity.this.runOnUiThread(new Runnable() {
  130. @Override
  131. public void run() {
  132. switch (num){
  133. case 200:
  134. Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
  135. break;
  136. case 400:
  137. Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();
  138. break;
  139. default:
  140. Toast.makeText(MainActivity.this, "请求成功,登录失败,返回码:"+num, Toast.LENGTH_LONG).show();
  141. break;
  142. }
  143. }
  144. });
  145. }
  146. }

转载于:https://www.cnblogs.com/Mr-Deng/p/11313961.html

发表评论

表情:
评论列表 (有 0 条评论,192人围观)

还没有评论,来说两句吧...

相关阅读