文档章节

使用okHttp登录、Md5密码加密

o
 osc_wws45aot
发布于 2019/08/21 15:51
字数 1076
阅读 12
收藏 0

1、使用okHttp3登录

2、Md5密码加密

3、完整代码

4、项目案例

 

使用okHttp3登录:

使用okHttp3之前要在build.gradle引入okHttp3的依赖(顺便引入解析数据的gson)

implementation 'com.squareup.okhttp3:okhttp:3.4.1' //okhttp3
implementation 'com.google.code.gson:gson:2.7' //导入gson

在AndroidManifest.xml中加入网络请求权限

<uses-permission android:name="android.permission.INTERNET" />

我在这里封装好了okHttp3的登录类:

package com.example.login;

import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttp {
    private static MediaType mediaType;

    //登录
    public static void Login(String url,String number,String password,okhttp3.Callback callback){
        try {
            OkHttpClient client = new OkHttpClient();
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("number",number.toString());
            jsonObject.put("password",password.toString());
            mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
            Request request = new Request.Builder().url(url).post(requestBody).build();
            client.newCall(request).enqueue(callback);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

 然后使用(在线程中使用):     

String number = edt_number.getText().toString(); //获取文本框输入的账号
String password = edt_number.getText().toString(); //获取文本框输入的密码
String url = "http://XXX/login"; //获取url,这里加上自己的登录url
OkHttp.Login(url,number,password, new okhttp3.Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.d("失败","错误");
    }

     @Override
     public void onResponse(Call call, final Response response) throws IOException {
        if(response.code() == 200){
        Gson gson = new Gson();
        String data = response.body().string();
        final Emp emp = gson.fromJson(data,Emp.class); //新加了一个人员类
        Log.d("成功","姓名:" + emp.getName());
        runOnUiThread(new Runnable() {
               @Override
               public void run() {
                      btn_login.setText(emp.getName());
               }
         });
         }else{
                Log.d("成功","获取失败");
          }
      }
});

Md5密码加密(两种加密,看个人需求,普通Md5加密、自定义Md5加密):

Md5加密(代码):

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

 普通加密使用(直接在获取文本框密码中加密):

String password = md5Decode(edt_password.getText().toString()); //加密 //获取文本框输入的密码

 自定义加密使用(在后面加了一段乱码,后台中的加密同时也要加上这段乱码):

String password = md5Decode(edt_password.getText().toString() +"dabsdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,");

 完整代码(MainActivity的代码):

package com.example.login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText edt_number,edt_password;
    private Button btn_login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){
        edt_number = (EditText)findViewById(R.id.edt_number);
        edt_password = (EditText)findViewById(R.id.edt_password);
        btn_login = (Button)findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        String number = edt_number.getText().toString(); //获取文本框中的账号
        //获取文本框中的密码,MD5加密
        String password = md5Decode(edt_password.getText().toString() +"dabsdafaqj23ou89ZXcj@#$@#$#@KJdjklj;D../dSF.,");
        String url = ""; //登录的url
        OkHttp.Login(url,number,password, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("失败","错误");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if(response.code() == 200){
                    Gson gson = new Gson();
                    String data = response.body().string();
                    final Emp emp = gson.fromJson(data,Emp.class);
                    Log.d("成功","姓名:" + emp.getName());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_login.setText(emp.getName());
                    }
                });
                }else{
                    Log.d("成功","获取失败");
                }
            }
        });
    }


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

}

 MainActivity的布局代码:

<?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:orientation="vertical"
    android:paddingTop="10dp"
    android:paddingRight="10dp"
    android:paddingLeft="10dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/edt_number"
        android:gravity="center_horizontal|center_vertical"
        android:lines="1"
        android:maxLength="12"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:hint="请输入账号"
        tools:ignore="MissingConstraints" />
    <EditText
        android:id="@+id/edt_password"
        android:gravity="center_horizontal|center_vertical"
        android:lines="1"
        android:maxLength="12"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:hint="请输入密码"
        android:inputType="textPassword"
        tools:ignore="MissingConstraints" />
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"/>

</LinearLayout>

 OkHttp封装类代码:

package com.example.login;

import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class OkHttp {
    private static MediaType mediaType;

    //登录
    public static void Login(String url,String number,String password,okhttp3.Callback callback){
        try {
            OkHttpClient client = new OkHttpClient();
            JSONObject jsonObject =new JSONObject();
            jsonObject.put("number",number.toString());
            jsonObject.put("password",password.toString());
            mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
            Request request = new Request.Builder().url(url).post(requestBody).build();
            client.newCall(request).enqueue(callback);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

 Emp人员类:

package com.example.login;

public class Emp {
    private String number;
    private String name;
    public Emp(String number,String name){
        this.number = number;
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 项目案例(点击获取,提取码:oi87),项目中有两个案例app的是页面传值,login是本章的登录

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

OSChina 周五乱弹 —— 你大妈还是你大妈

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 @watergood:是时候分享一波我的这张纯音乐歌单了,过去的五年多时间里,我陆陆续续地把听到的好听的纯音乐添加了进去,目前一共65首,相信总...

小小编辑
今天
25
0
在Objective-C中生成随机数 - Generating random numbers in Objective-C

问题: I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method: 我主要是Java头,我想要一种生成0到74之间的伪随......

技术盛宴
今天
13
0
ftp-ftps-sftp的关系

Ftp FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作...

独钓渔
今天
12
0
使Vim将所有空格显示为字符 - Make Vim show ALL white spaces as a character

问题: I can't find a way to make Vim show all white spaces as a character. 我找不到让Vim将所有空白显示为字符的方法。 All I found was about tabs, trailing spaces etc. 我发现的只......

富含淀粉
今天
23
0
RN 接入高德地图遇到的一些问题

react-native-amap-geolocation、react-native-amap3d 1、iOS Geolocation.getCurrentPosition 获取坐标后,没有返回 address 信息? 逆地理编码 Android 默认返回逆地理编码,而 iOS 需要手...

Jack088
今天
14
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部