admin管理员组

文章数量:1026989

安卓开发中记录

安卓开发记录

安卓中解析json

 导入包:import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;// 封装一个方法如下:public void dealWithJson(String ret){try {// 构造json对象JSONObject jsonObj = new JSONObject(ret);if(!jsonObj.has("txnNo")) // 判断json中是否包含字段"txnNo"{System.out.println("加密字段不在json中!");return;}if(jsonObj.get("txnNo").toString()!="") // 获取字段对应的值{String content= cn.roylionmon.util.AES128ECB.decryptHex(jsonObj.get("txnNo").toString(),"1234567812345678");if(content==null){System.out.println("解密出错!");Toast tmp = Toast.makeText(MainActivity.this, "解密出错!估计是字段越界", Toast.LENGTH_SHORT);// 设置其位置为居中tmp.setGravity(Gravity.CENTER,0,0);tmp.show();}else {String result = content.substring(content.length() - 6); // 截取字符串后六位tipView.setText("第一次验证码:" + result);}}else {tipView.setText("加密字段是空的!");}}catch (JSONException e)  // 捕获异常{e.printStackTrace();}}}

安卓访问https和http

在AndroidManifest.xml文件中新增权限: <uses-permission android:name="android.permission.INTERNET"></uses-permission>
发现只能访问https无法访问http?
解决方法:在工程res下面新建一个xml文件夹,在文件夹中新建后缀为xml文件(比如:allow_http.xml)在allow_http.xml中添加如下内容:<?xml version="1.0" encoding="utf-8"?><network-security-config><base-config cleartextTrafficPermitted="true" /></network-security-config>在AndroidManifest.xml文件中新增 android:networkSecurityConfig="@xml/network_allow_http"位子如下:<applicationandroid:allowBackup="true"android:icon="@mipmap/ico"android:label="@string/app_name"android:networkSecurityConfig="@xml/network_allow_http"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".Main2Activity"></activity><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application>

安卓中创建线程并发起http请求:

导入包:import java.HttpURLConnection;import java.URL;import java.io.BufferedReader;import java.io.DataOutput;import java.io.DataOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.IOException;例如:// 封装一个方法public void dealHttpPost(String type) {   // 线程处理函数 type 是类型 POST 或者GETnew Thread(new Runnable() {  // 创建一个线程对象@Override public void run() {HttpURLConnection connection = null;BufferedReader reader =null;try{URL url =new URL(gurlEdit.getText().toString());connection =(HttpURLConnection) url.openConnection();connection.setRequestMethod(type);connection.setConnectTimeout(8000);connection.setReadTimeout(8000);// 使用HttpURLConnection发送post请求并携带json内容connection.setRequestProperty("Content-type", "application/json");connection.setDoOutput(true);connection.setUseCaches(false);connection.connect();JSONObject jsonObject = new JSONObject();jsonObject.put("userName", "陈冠希");jsonObject.put("passwd", "e10adc3949ba59abbe56e057f20f883e");jsonObject.put("nickName", "edison");jsonObject.put("phone", "17212345632");jsonObject.put("email", "475546280@qq");// 传入参数OutputStream outputStream = connection.getOutputStream();outputStream.write(jsonObject.toString().getBytes("utf-8"));outputStream.flush();//获取服务器返回的数据InputStream in =connection.getInputStream();reader = new BufferedReader(new InputStreamReader(in));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine())!=null){response.append(line);}//    Log.d("button", "show: ok"+response.toString());showDataInTextView(response.toString());}catch (Exception e){e.printStackTrace();}finally {if(reader!=null){try{reader.close();}catch (IOException e){e.printStackTrace();}}if (connection!=null){connection.disconnect();}}}}).start();}

安卓中AES128ECB加密(安卓使用AES128加密,ECB加密模式,PKCS5Padding填充,utf-8格式,hex输出)

 // 封装一个类public class AES128ECB{private static final String ENCRY_ALGORITHM = "AES";               // 加密模式private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";  // 填充方式private static final String IV_ = null;                            // 无需设置vi偏移private static final String CHARACTER = "UTF-8";                   // 字符集private static final int PWD_SIZE = 16;                            // 加密密钥长度不足16位的补0/*** 密码处理方法* 如果加解密出问题,* 请先查看本方法,排除密码长度不足补"0",导致密码不一致* @param password 待处理的密码* @return* @throws UnsupportedEncodingException*/private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {byte[] data = null;if (password == null) {password = "";}StringBuffer sb = new StringBuffer(PWD_SIZE);sb.append(password);while (sb.length() < PWD_SIZE) {sb.append("0");}if (sb.length() > PWD_SIZE) {sb.setLength(PWD_SIZE);}data = sb.toString().getBytes("UTF-8");return data;}//======================>原始加密<======================/*** 原始加密* @param clearTextBytes 明文字节数组,待加密的字节数组* @param pwdBytes 加密密码字节数组* @return 返回加密后的密文字节数组,加密错误返回null*/public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {try {// 1 获取加密密钥SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);// 2 获取Cipher实例Cipher cipher = Cipher.getInstance(CIPHER_MODE);// 查看数据块位数 默认为16(byte) * 8 =128 bit
//            System.out.println("数据块位数(byte):" + cipher.getBlockSize());// 3 初始化Cipher实例。设置执行模式以及加密密钥cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 4 执行byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);// 5 返回密文字符集return cipherTextBytes;} catch (NoSuchPaddingException e) {e.printStackTrace();}catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return null;}/*** 原始解密* @param cipherTextBytes 密文字节数组,待解密的字节数组* @param pwdBytes 解密密码字节数组* @return 返回解密后的明文字节数组,解密错误返回null*/public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {try {// 1 获取解密密钥SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);// 2 获取Cipher实例Cipher cipher = Cipher.getInstance(CIPHER_MODE);// 查看数据块位数 默认为16(byte) * 8 =128 bit
//            System.out.println("数据块位数(byte):" + cipher.getBlockSize());// 3 初始化Cipher实例。设置执行模式以及加密密钥cipher.init(Cipher.DECRYPT_MODE, keySpec);// 4 执行byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);// 5 返回明文字符集return clearTextBytes;} catch (InvalidKeyException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 解密错误 返回nullreturn null;}//======================>HEX<======================/*** HEX加密* @param clearText 明文,待加密的内容* @param password 密码,加密的密码* @return 返回密文,加密后得到的内容。加密错误返回null*/public static String encryptHex(String clearText, String password) {try {// 1 获取加密密文字节数组byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));// 2 对密文字节数组进行 转换为 HEX输出密文String cipherText = byte2hex(cipherTextBytes);// 3 返回 HEX输出密文return cipherText;} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 加密错误返回nullreturn null;}/*** HEX解密* @param cipherText 密文,带解密的内容* @param password 密码,解密的密码* @return 返回明文,解密后得到的内容。解密错误返回null*/public static String decryptHex(String cipherText, String password) {try {// 1 将HEX输出密文 转为密文字节数组byte[] cipherTextBytes = hex2byte(cipherText);// 2 将密文字节数组进行解密 得到明文字节数组byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));// 3 根据 CHARACTER 转码,返回明文字符串return new String(clearTextBytes, CHARACTER);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 解密错误返回nullreturn null;}/*字节数组转成16进制字符串  */public static String byte2hex(byte[] bytes) { // 一个字节的数,StringBuffer sb = new StringBuffer(bytes.length * 2);String tmp = "";for (int n = 0; n < bytes.length; n++) {// 整数转成十六进制表示tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));if (tmp.length() == 1) {sb.append("0");}sb.append(tmp);}return sb.toString();//.toUpperCase(); // 转成大写}/*将hex字符串转换成字节数组 */private static byte[] hex2byte(String str) {if (str == null || str.length() < 2) {return new byte[0];}str = str.toLowerCase();int l = str.length() / 2;byte[] result = new byte[l];for (int i = 0; i < l; ++i) {String tmp = str.substring(2 * i, 2 * i + 2);result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);}return result;}/* public static void main(String[] args) {String test = encryptHex("1619331162259", "1234567812345678");System.out.println(test);//System.out.println(decryptHex("3633f19a00631932aac1a254d4acae89", "1234567812345678"));}*/
}   

安卓开发中记录

安卓开发记录

安卓中解析json

 导入包:import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;// 封装一个方法如下:public void dealWithJson(String ret){try {// 构造json对象JSONObject jsonObj = new JSONObject(ret);if(!jsonObj.has("txnNo")) // 判断json中是否包含字段"txnNo"{System.out.println("加密字段不在json中!");return;}if(jsonObj.get("txnNo").toString()!="") // 获取字段对应的值{String content= cn.roylionmon.util.AES128ECB.decryptHex(jsonObj.get("txnNo").toString(),"1234567812345678");if(content==null){System.out.println("解密出错!");Toast tmp = Toast.makeText(MainActivity.this, "解密出错!估计是字段越界", Toast.LENGTH_SHORT);// 设置其位置为居中tmp.setGravity(Gravity.CENTER,0,0);tmp.show();}else {String result = content.substring(content.length() - 6); // 截取字符串后六位tipView.setText("第一次验证码:" + result);}}else {tipView.setText("加密字段是空的!");}}catch (JSONException e)  // 捕获异常{e.printStackTrace();}}}

安卓访问https和http

在AndroidManifest.xml文件中新增权限: <uses-permission android:name="android.permission.INTERNET"></uses-permission>
发现只能访问https无法访问http?
解决方法:在工程res下面新建一个xml文件夹,在文件夹中新建后缀为xml文件(比如:allow_http.xml)在allow_http.xml中添加如下内容:<?xml version="1.0" encoding="utf-8"?><network-security-config><base-config cleartextTrafficPermitted="true" /></network-security-config>在AndroidManifest.xml文件中新增 android:networkSecurityConfig="@xml/network_allow_http"位子如下:<applicationandroid:allowBackup="true"android:icon="@mipmap/ico"android:label="@string/app_name"android:networkSecurityConfig="@xml/network_allow_http"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".Main2Activity"></activity><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application>

安卓中创建线程并发起http请求:

导入包:import java.HttpURLConnection;import java.URL;import java.io.BufferedReader;import java.io.DataOutput;import java.io.DataOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.IOException;例如:// 封装一个方法public void dealHttpPost(String type) {   // 线程处理函数 type 是类型 POST 或者GETnew Thread(new Runnable() {  // 创建一个线程对象@Override public void run() {HttpURLConnection connection = null;BufferedReader reader =null;try{URL url =new URL(gurlEdit.getText().toString());connection =(HttpURLConnection) url.openConnection();connection.setRequestMethod(type);connection.setConnectTimeout(8000);connection.setReadTimeout(8000);// 使用HttpURLConnection发送post请求并携带json内容connection.setRequestProperty("Content-type", "application/json");connection.setDoOutput(true);connection.setUseCaches(false);connection.connect();JSONObject jsonObject = new JSONObject();jsonObject.put("userName", "陈冠希");jsonObject.put("passwd", "e10adc3949ba59abbe56e057f20f883e");jsonObject.put("nickName", "edison");jsonObject.put("phone", "17212345632");jsonObject.put("email", "475546280@qq");// 传入参数OutputStream outputStream = connection.getOutputStream();outputStream.write(jsonObject.toString().getBytes("utf-8"));outputStream.flush();//获取服务器返回的数据InputStream in =connection.getInputStream();reader = new BufferedReader(new InputStreamReader(in));StringBuilder response = new StringBuilder();String line;while ((line = reader.readLine())!=null){response.append(line);}//    Log.d("button", "show: ok"+response.toString());showDataInTextView(response.toString());}catch (Exception e){e.printStackTrace();}finally {if(reader!=null){try{reader.close();}catch (IOException e){e.printStackTrace();}}if (connection!=null){connection.disconnect();}}}}).start();}

安卓中AES128ECB加密(安卓使用AES128加密,ECB加密模式,PKCS5Padding填充,utf-8格式,hex输出)

 // 封装一个类public class AES128ECB{private static final String ENCRY_ALGORITHM = "AES";               // 加密模式private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";  // 填充方式private static final String IV_ = null;                            // 无需设置vi偏移private static final String CHARACTER = "UTF-8";                   // 字符集private static final int PWD_SIZE = 16;                            // 加密密钥长度不足16位的补0/*** 密码处理方法* 如果加解密出问题,* 请先查看本方法,排除密码长度不足补"0",导致密码不一致* @param password 待处理的密码* @return* @throws UnsupportedEncodingException*/private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {byte[] data = null;if (password == null) {password = "";}StringBuffer sb = new StringBuffer(PWD_SIZE);sb.append(password);while (sb.length() < PWD_SIZE) {sb.append("0");}if (sb.length() > PWD_SIZE) {sb.setLength(PWD_SIZE);}data = sb.toString().getBytes("UTF-8");return data;}//======================>原始加密<======================/*** 原始加密* @param clearTextBytes 明文字节数组,待加密的字节数组* @param pwdBytes 加密密码字节数组* @return 返回加密后的密文字节数组,加密错误返回null*/public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {try {// 1 获取加密密钥SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);// 2 获取Cipher实例Cipher cipher = Cipher.getInstance(CIPHER_MODE);// 查看数据块位数 默认为16(byte) * 8 =128 bit
//            System.out.println("数据块位数(byte):" + cipher.getBlockSize());// 3 初始化Cipher实例。设置执行模式以及加密密钥cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 4 执行byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);// 5 返回密文字符集return cipherTextBytes;} catch (NoSuchPaddingException e) {e.printStackTrace();}catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return null;}/*** 原始解密* @param cipherTextBytes 密文字节数组,待解密的字节数组* @param pwdBytes 解密密码字节数组* @return 返回解密后的明文字节数组,解密错误返回null*/public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {try {// 1 获取解密密钥SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);// 2 获取Cipher实例Cipher cipher = Cipher.getInstance(CIPHER_MODE);// 查看数据块位数 默认为16(byte) * 8 =128 bit
//            System.out.println("数据块位数(byte):" + cipher.getBlockSize());// 3 初始化Cipher实例。设置执行模式以及加密密钥cipher.init(Cipher.DECRYPT_MODE, keySpec);// 4 执行byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);// 5 返回明文字符集return clearTextBytes;} catch (InvalidKeyException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 解密错误 返回nullreturn null;}//======================>HEX<======================/*** HEX加密* @param clearText 明文,待加密的内容* @param password 密码,加密的密码* @return 返回密文,加密后得到的内容。加密错误返回null*/public static String encryptHex(String clearText, String password) {try {// 1 获取加密密文字节数组byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));// 2 对密文字节数组进行 转换为 HEX输出密文String cipherText = byte2hex(cipherTextBytes);// 3 返回 HEX输出密文return cipherText;} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 加密错误返回nullreturn null;}/*** HEX解密* @param cipherText 密文,带解密的内容* @param password 密码,解密的密码* @return 返回明文,解密后得到的内容。解密错误返回null*/public static String decryptHex(String cipherText, String password) {try {// 1 将HEX输出密文 转为密文字节数组byte[] cipherTextBytes = hex2byte(cipherText);// 2 将密文字节数组进行解密 得到明文字节数组byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));// 3 根据 CHARACTER 转码,返回明文字符串return new String(clearTextBytes, CHARACTER);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 解密错误返回nullreturn null;}/*字节数组转成16进制字符串  */public static String byte2hex(byte[] bytes) { // 一个字节的数,StringBuffer sb = new StringBuffer(bytes.length * 2);String tmp = "";for (int n = 0; n < bytes.length; n++) {// 整数转成十六进制表示tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));if (tmp.length() == 1) {sb.append("0");}sb.append(tmp);}return sb.toString();//.toUpperCase(); // 转成大写}/*将hex字符串转换成字节数组 */private static byte[] hex2byte(String str) {if (str == null || str.length() < 2) {return new byte[0];}str = str.toLowerCase();int l = str.length() / 2;byte[] result = new byte[l];for (int i = 0; i < l; ++i) {String tmp = str.substring(2 * i, 2 * i + 2);result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);}return result;}/* public static void main(String[] args) {String test = encryptHex("1619331162259", "1234567812345678");System.out.println(test);//System.out.println(decryptHex("3633f19a00631932aac1a254d4acae89", "1234567812345678"));}*/
}   

本文标签: 安卓开发中记录