zoukankan      html  css  js  c++  java
  • 登录(记住账号密码、获取后台数据)

    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”同步)

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

     activity_mian.xml样式文件

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
    
        <ImageView
            android:id="@+id/iv"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp"
            android:background="@drawable/dongman"/>
    
        <LinearLayout
            android:id="@+id/ll_number"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/iv"
            android:layout_centerVertical="true"
            android:layout_marginTop="15dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="5dp"
            android:background="#ffffff">
    
            <TextView
                android:id="@+id/tv_number"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="账号"
                android:textColor="#000"
                android:textSize="20sp"/>
            <EditText
                android:id="@+id/et_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:background="@null"
                android:padding="10dp"/>
        </LinearLayout>
    
    
        <LinearLayout
            android:id="@+id/ll_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ll_number"
            android:layout_centerVertical="true"
            android:layout_marginTop="15dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="5dp"
            android:background="#ffffff">
    
            <TextView
                android:id="@+id/tv_password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="密码"
                android:textColor="#000"
                android:textSize="20sp"/>
            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:background="@null"
                android:padding="10dp"/>
        </LinearLayout>
        <Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/ll_password"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="30dp"
            android:text="登录"
            android:background="#3C8DC4"
            android:textSize="20sp"/>
    
    
    </RelativeLayout>
    

     创建保存账号密码类

    package com.example.remembernp;
    
    import android.content.Context;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    public class SaveFile {
        //把账号密码保存在data.txt文件中
        public static boolean saveUserInfo(Context context, String number, String password){
            try{
                FileOutputStream fos = context.openFileOutput("data.txt",Context.MODE_PRIVATE);
                fos.write((number + ":" + password).getBytes());
                fos.close();
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        //从data.txt中去获取刚刚保存的账号密码
        public static Map<String,String> getUserInfo(Context context) {
            String content = "";
            try {
                FileInputStream fis = context.openFileInput("data.txt");
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);//读取
                content = new String(buffer);
                Map<String ,String > userMap = new HashMap<String, String>();
                String[] infos = content.split(":");
                userMap.put("number",infos[0]);
                userMap.put("password",infos[1]);
                fis.close();
                return userMap;
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
    
        }
    }
    

     主页代码

    package com.example.remembernp;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.app.AlertDialog;
    import android.icu.util.LocaleData;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Map;
    
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.MediaType;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
        private EditText etNumber;
        private EditText etPassword;
        private Button btnLogin;
        private MediaType mediaType;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button btn = (Button)findViewById(R.id.btn_login);
            Map<String,String> userInfo = SaveFile.getUserInfo(this);
            initView();
            if(userInfo != null){
                etNumber.setText(userInfo.get("number"));
                etPassword.setText(userInfo.get("password"));
            }
        }
    
        private void  initView(){
            etNumber = (EditText)findViewById(R.id.et_number);
            etPassword = (EditText)findViewById(R.id.et_password);
            btnLogin = (Button)findViewById(R.id.btn_login);
            btnLogin.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View view) {
            //单击事件,获取账号密码
            final String number = etNumber.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            //检查账号密码是否正确
            if(TextUtils.isEmpty(number)){
                Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(password)){
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }
            okHttp(); //登录
        }
    
        private void okHttp(){
            //单击事件,获取账号密码
            final String number = etNumber.getText().toString().trim();
            final String password = etPassword.getText().toString().trim();
            //给密码加密
            final String md5 = md5Decode(password + "dabsdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("number",number);
                        jsonObject.put("password",md5);
                        mediaType = MediaType.parse("application/json;charest=utf-8");
                        RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
                        final Request request = new Request.Builder() .url("使用自己的登录网址")
                                .post(requestBody).build();
                        client.newCall(request).enqueue(new Callback() {
                            @Override
                            //请求失败
                            public void onFailure(Call call, IOException e) {
                                Log.d("请求失败",",返回码:"+e.getMessage());
                                loginRemind(400);
                            }
    
                            @Override
                            //请求成功
                            public void onResponse(Call call, final Response response) throws IOException {
                                loginRemind(response.code());
                                if(response.code() == 200){
                                    Log.d("请求成功---------","后台返回数据:"+response.body().string());
                                    //保存账号密码
                                    SaveFile.saveUserInfo(MainActivity.this,number,password);
                                }else{
                                    Log.d("请求成功-----但登录失败----返回码:"+response.code(),"------失败原因:"+response.body().string());
                                }
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
        public String md5Decode(String content) {
            byte[] hash;
            try {
                hash = MessageDigest.getInstance("MD5").digest(content.getBytes("UTF-8"));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("NoSuchAlgorithmException", e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("UnsupportedEncodingException", e);
            }
            //对生成的16字节数组进行补零操作
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }
    
        private void loginRemind(final int num){
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    switch (num){
                        case 200:
                            Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                            break;
                        case 400:
                            Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_LONG).show();
                            break;
                        default:
                            Toast.makeText(MainActivity.this, "请求成功,登录失败,返回码:"+num, Toast.LENGTH_LONG).show();
                            break;
                    }
                }
            });
        }
    }
    
  • 相关阅读:
    C++(函数默认参数)
    C++(引用六)
    C++(引用五)
    C++(引用四)
    C++(引用三)
    C++(引用二)
    C++(引用一)
    划水。。。
    2019.11.7
    lyc——2019.10.31
  • 原文地址:https://www.cnblogs.com/Mr-Deng/p/11313961.html
Copyright © 2011-2022 走看看