# 安卓实例讲解

安卓代码请求实例讲解

# 简单描述

讲解安卓不带加解密简单使用实例,实例使用弹窗登陆卡密验证方式,参数为mac设备号,以及cardStr卡密内容,请求方式为POST请求, 当用户点击按钮触发click事件,触发事件创建线程调用Demo类下的login方法

Button button = new Button(this);
button.setText("LOGIN");
button.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View var1) {
        Toast.makeText(context, "Connecting...", 0).show();
        (new Thread(new Verify())).start();
    }
});
1
2
3
4
5
6
7
8
9

以下是Demo类请求:

public class Verify implements Runnable{
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void run() {
        OutputStream outputStream=null;
        String result="";
        try {
            JSONObject param = new JSONObject();
            param.put("cardStr","测试卡密");
            param.put("mac","测试设备号");
            URL url=new URL("https://api.potatocloud.cn/api/verifyCardV2");
            HttpURLConnection  connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            //设置请求方式 GET / POST 一定要大小
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(false);
            // 设置请求头格式为json
            connection.setRequestProperty("Content-Type", "application/json");
            // 设置askKey,内容请在APP设置内复制
            connection.setRequestProperty("askKey", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6NjU3ODA1MTEyMzg5NDg4NjQwLCJnZXRNYW5hZ2VtZW50SWQiOjY0NTQzMTk2OTMzNTMwMDA5NiwiVElNRSI6MTY0OTk0NDQwMjE4Nn0.oDxg5d6AoE-gkMABpiBAI7Z5q77EDR5Nrh9ZWoCB9i0");
            // 验签数据
            connection.setRequestProperty("sign", "application/json");
            outputStream = connection.getOutputStream();
            outputStream.write(param.toString().getBytes());
            outputStream.flush();
            outputStream.close();
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                // 判断HTTP状态码
                return;
            }
            // 获取请求返回结果
            result=getStringByStream(connection.getInputStream());
            JSONObject jsonObject = new JSONObject(result);
            String code = jsonObject.getString("code");
            if (code.equals("200")){
                //校验
                JSONObject data = jsonObject.getJSONObject("data");
                // 验证成功,获取参数
                return;
            }else {
                // 请求失败,获取message展示给用户
                String message=jsonObject.getString("message");
                return;
            }

        } catch (Exception e) {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
           // 验证失败
            return;
        }
    }
   /**
   * 解析返回方法
   */
   public static String getStringByStream(InputStream inputStream){
           Reader reader;
           try {
               reader=new InputStreamReader(inputStream,"UTF-8");
               char[] rawBuffer=new char[512];
               StringBuffer buffer=new StringBuffer();
               int length;
               while ((length=reader.read(rawBuffer))!=-1){
                   buffer.append(rawBuffer,0,length);
               }
               return buffer.toString();
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
           return null;
       }

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

有能力的可以自行封装请求工具类,自行调用,GET请求一样

# 安卓加解密

AEC加密方法

 /**
     * 加密算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * AES 的 密钥长度,32 字节,范围:16 - 32 字节
     */
    public static final int SECRET_KEY_LENGTH = 32;

    /**
     * 字符编码
     */
    private static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8;

    /**
     * 秘钥长度不足 16 个字节时,默认填充位数
     */
    private static final String DEFAULT_VALUE = "0";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    public static String encrypt(String data, String secretKey) {
        try {
            //创建密码器
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            //初始化为加密密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(secretKey));
            // 加密操作
            byte[] encryptByte = cipher.doFinal(data.getBytes(CHARSET_UTF8));
            // 将加密以后的数据进行 Base64 编码
            return base64Encode(encryptByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用密码获取 AES 秘钥
     * @return
     */
    public static Key getSecretKey(String secretKey) {
        secretKey = toMakeKey(secretKey, SECRET_KEY_LENGTH, DEFAULT_VALUE);
        return new SecretKeySpec(secretKey.getBytes(CHARSET_UTF8), KEY_ALGORITHM);
    }

    private static String toMakeKey(String secretKey, int length, String text) {
        // 获取密钥长度
        int strLen = secretKey.length();
        // 判断长度是否小于应有的长度
        if (strLen < length) {
            // 补全位数
            StringBuilder builder = new StringBuilder();
            // 将key添加至builder中
            builder.append(secretKey);
            // 遍历添加默认文本
            for (int i = 0; i < length - strLen; i++) {
                builder.append(text);
            }
            // 赋值
            secretKey = builder.toString();
        }
        return secretKey;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

AEC解密方法


 /**
     * 加密算法
     */
    private static final String KEY_ALGORITHM = "AES";

    /**
     * AES 的 密钥长度,32 字节,范围:16 - 32 字节
     */
    public static final int SECRET_KEY_LENGTH = 32;

    /**
     * 字符编码
     */
    private static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8;

    /**
     * 秘钥长度不足 16 个字节时,默认填充位数
     */
    private static final String DEFAULT_VALUE = "0";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    public static String decrypt(String base64Data, String secretKey) {
        try {
            // base64解码
            byte[] data = base64Decode(base64Data);
            //创建密码器
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            //设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(secretKey));
            //执行解密操作
            byte[] result = cipher.doFinal(data);
            // 返回字符串
            return new String(result, CHARSET_UTF8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用密码获取 AES 秘钥
     * @return
     */
    public static Key getSecretKey(String secretKey) {
        secretKey = toMakeKey(secretKey, SECRET_KEY_LENGTH, DEFAULT_VALUE);
        return new SecretKeySpec(secretKey.getBytes(CHARSET_UTF8), KEY_ALGORITHM);
    }

    private static String toMakeKey(String secretKey, int length, String text) {
        // 获取密钥长度
        int strLen = secretKey.length();
        // 判断长度是否小于应有的长度
        if (strLen < length) {
            // 补全位数
            StringBuilder builder = new StringBuilder();
            // 将key添加至builder中
            builder.append(secretKey);
            // 遍历添加默认文本
            for (int i = 0; i < length - strLen; i++) {
                builder.append(text);
            }
            // 赋值
            secretKey = builder.toString();
        }
        return secretKey;
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

Base64加密

    public static String base64Encode(byte[] data) {
        return Base64.encodeToString(data, Base64.NO_WRAP);
    }

1
2
3
4

Base64解密

    public static byte[] base64Decode(String data) {
        return Base64.decode(data, Base64.NO_WRAP);
    }

1
2
3
4

Md5 加密方法

    public String getMD5(String info){
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();
            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++){
                if (Integer.toHexString(0xff & encryption[i]).length() == 1){
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                }
                else{
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        }catch (NoSuchAlgorithmException e){
            return "";
        }catch (UnsupportedEncodingException e){
            return "";
        }
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
lastUpdate: 7/25/2024, 4:20:09 PM