編輯:關於 Android 程式設計
網路應用為了保護使用者隱私,通常會用「帳號+密碼」做驗證。很多網站還會加一層防護:連續登入失敗若干次後強制要求輸入驗證碼,避免惡意程式用機械式暴力破解密碼。那麼在 Android 上怎麼做到同樣的事?
有些人會覺得這增加了使用門檻,多數 App 並不這麼設計。先不論它是否必要,本文的目標就是把它做出來。內容包含兩塊:一、使用者連續多次輸錯密碼後增加驗證碼驗證;二、Android 如何透過 HTTP 請求與伺服器通訊。
提供一個可直接複用的驗證碼產生類:
//生成二維碼的類 public class BPUtil { /** * 用於生成二維碼的字符 */ private static final char[] CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a','b','c','d','e','f','g','h','i','j','k','m','l','n','o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','M','L','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' }; private static BPUtil bpUtil; public static BPUtil getInstance() { if(bpUtil == null) bpUtil = new BPUtil(); return bpUtil; } // width="60" height="30" // base_padding_left="5" // range_padding_left="10" // base_padding_top="15" // range_padding_top="10" // codeLength="4" // line_number="3" // font_size="20" //default settings private static final int DEFAULT_CODE_LENGTH = 4; private static final int DEFAULT_FONT_SIZE = 20; private static final int DEFAULT_LINE_NUMBER = 3; private static final int BASE_PADDING_LEFT = 5, RANGE_PADDING_LEFT = 10, BASE_PADDING_TOP = 15, RANGE_PADDING_TOP = 10; private static final int DEFAULT_WIDTH = 60, DEFAULT_HEIGHT = 30; //settings decided by the layout xml //canvas width and height private int width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT; //random word space and pading_top private int base_padding_left = BASE_PADDING_LEFT, range_padding_left = RANGE_PADDING_LEFT, base_padding_top = BASE_PADDING_TOP, range_padding_top = RANGE_PADDING_TOP; //number of chars, lines; font size private int codeLength = DEFAULT_CODE_LENGTH, line_number = DEFAULT_LINE_NUMBER, font_size = DEFAULT_FONT_SIZE; //variables private String code; private int padding_left, padding_top; private Random random = new Random(); public Bitmap createBitmap() { padding_left = 0; Bitmap bp = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas c = new Canvas(bp); code = createCode(); c.drawColor(Color.WHITE); Paint paint = new Paint(); paint.setTextSize(font_size); for (int i = 0; i < code.length(); i++) { randomTextStyle(paint); randomPadding(); c.drawText(code.charAt(i) + "", padding_left, padding_top, paint); } for (int i = 0; i < line_number; i++) { drawLine(c, paint); } c.save( Canvas.ALL_SAVE_FLAG );//保存 c.restore();// return bp; } public String getCode() { return bpUtil.createCode(); } private String createCode() { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < codeLength; i++) { buffer.append(CHARS[random.nextInt(CHARS.length)]); } return buffer.toString(); } private void drawLine(Canvas canvas, Paint paint) { int color = randomColor(); int startX = random.nextInt(width); int startY = random.nextInt(height); int stopX = random.nextInt(width); int stopY = random.nextInt(height); paint.setStrokeWidth(1); paint.setColor(color); canvas.drawLine(startX, startY, stopX, stopY, paint); } private int randomColor() { return randomColor(1); } private int randomColor(int rate) { int red = random.nextInt(256) / rate; int green = random.nextInt(256) / rate; int blue = random.nextInt(256) / rate; return Color.rgb(red, green, blue); } private void randomTextStyle(Paint paint) { int color = randomColor(); paint.setColor(color); paint.setFakeBoldText(random.nextBoolean()); //true為粗體,false為非粗體 float skewX = random.nextInt(11) / 10; skewX = random.nextBoolean() ? skewX : -skewX; paint.setTextSkewX(skewX); //float類型參數,負數表示右斜,整數左斜 // paint.setUnderlineText(true); //true為下劃線,false為非下劃 // paint.setStrikeThruText(true); //true為刪除線,false為非刪除 } private void randomPadding() { padding_left += base_padding_left + random.nextInt(range_padding_left); padding_top = base_padding_top + random.nextInt(range_padding_top); } }
要達成的目標很明確:正常情況下帳號加密碼即可登入;一旦連續 3 次輸錯密碼,之後必須額外輸入驗證碼才能繼續嘗試。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/yanzheng" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" /> <EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_weight="6" android:layout_height="wrap_content" android:hint="@string/name_new" android:singleLine="true" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/password" /> <EditText android:id="@+id/pass" android:layout_weight="6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/pass_new" android:singleLine="true" /> </LinearLayout> <LinearLayout android:id="@+id/layout_yanzhengma" android:visibility="gone" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/yanzhengma" /> <TextView android:id="@+id/rander" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/rander_input" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <Button android:id="@+id/get" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/get" /> <Button android:id="@+id/post" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/post" /> </LinearLayout> </LinearLayout> </RelativeLayout>
驗證碼那一列 layout_yanzhengma 初始設為 gone,累計錯誤次數達標後再切換為可見。
public class MainActivity extends Activity { private TextView mytext = null; private EditText myname = null;//用戶名 private EditText mypass = null;//密碼 private EditText myrander = null;//驗證碼 private Button mygetbutton = null;//Get方式發送Http請求 private Button mypostbutton = null;//Post方式發送Http請求 private LinearLayout myline = null;//控制二維碼的顯示 private static int n = 0;//用戶輸錯密碼次數統計 static String name = null;//用戶輸入的用戶名 static String password = null;//用戶輸入的密碼 private String edit;//用戶輸入用戶輸入的驗證碼 private String code;//驗證碼 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mytext = (TextView)findViewById(R.id.rander); myname = (EditText)findViewById(R.id.name); mypass = (EditText)findViewById(R.id.pass); myrander = (EditText)findViewById(R.id.rander_input); mygetbutton = (Button)findViewById(R.id.get); mypostbutton = (Button)findViewById(R.id.post); myline = (LinearLayout)findViewById(R.id.layout_yanzhengma); mygetbutton.setOnClickListener(new mygetbutton()); mypostbutton.setOnClickListener(new mypostbutton()); } class mygetbutton implements OnClickListener{ public void onClick(View v) { name = myname.getText().toString(); password = mypass.getText().toString(); if(n>=3){//連續三次輸錯密碼 edit = myrander.getText().toString(); boolean boo = captcha (code , edit); if(boo){ new Thread(new Runnable() { public void run() { final boolean flag = SendServer.getsave(name, password); runOnUiThread(new Runnable() { public void run() { if(flag){ Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_SHORT).show(); n=0; }else{ Toast.makeText(MainActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show(); n++; if(n>=3){ myline.setVisibility(View.VISIBLE); } } } }); } }).start(); }else{ code = BPUtil.getInstance().getCode().toLowerCase();//生成新的二維碼 mytext.setText(code);//展示在用戶面前 } }else{ new Thread(new Runnable() { public void run() { final boolean flag = SendServer.getsave(name, password); runOnUiThread(new Runnable() { public void run() { if(flag){ Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_SHORT).show(); n=0; }else{ Toast.makeText(MainActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show(); n++; if(n>=3){ myline.setVisibility(1); code = BPUtil.getInstance().getCode().toLowerCase(); mytext.setText(code); } } } }); } }).start(); } } } class mypostbutton implements OnClickListener{ public void onClick(View v) { name = myname.getText().toString(); password = mypass.getText().toString(); new Thread(new Runnable() { public void run() { final boolean flag = SendServer.postsave(name, password); runOnUiThread(new Runnable() { @Override public void run() { if(flag){ Toast.makeText(MainActivity.this, "登錄成功", Toast.LENGTH_SHORT).show(); n=0; }else{ Toast.makeText(MainActivity.this, "登錄失敗", Toast.LENGTH_SHORT).show(); n++; if(n>=3){ myline.setVisibility(1); } } } }); } }).start(); } } @SuppressLint("ShowToast") private boolean captcha (String code , String edit) { boolean flag = false; if (code.equals(edit)) { flag = true; }else { flag = false; Toast.makeText(MainActivity.this, " 驗證碼錯誤", 0).show(); // imageview.setImageBitmap(bitmap); } return flag; } protected void onRestart() { super.onRestart(); n=0; } protected void onDestroy() { super.onDestroy(); n=0; } }
這裡寫了兩個按鈕,一個走 GET 驗證、一個走 POST 驗證,功能等價,純粹為了對照兩種請求方式。幾個細節:n 是失敗次數計數器,登入成功即歸零;myline 控制驗證碼列的顯示與隱藏;onRestart 與 onDestroy 都會把 n 歸零,方便重新體驗流程。另外提醒一下,網路請求都包在子執行緒裡,回主執行緒更新 UI 用 runOnUiThread,這是避免 NetworkOnMainThreadException 的必要寫法。
public class SendServer { //GET方式請求 public static boolean getsave(String name, String password) { boolean flag = false; HttpURLConnection conn = null; try { //防止中文亂碼 String username = URLEncoder.encode(name, "UTF-8"); String userpassword = URLEncoder.encode(password, "UTF-8"); URL url = new URL("https://10.20.90.3:8080/Register/ManageServlet?"+"name="+username+"&password="+userpassword); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); int responseCode = conn.getResponseCode(); if(responseCode == 200){ InputStream is = conn.getInputStream(); String stu = getStringFromInputStream(is); if(stu.equals("登錄成功")){ flag = true; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally{ if(conn != null){ conn.disconnect(); //關閉連接 } } return flag; } //POST請求 public static boolean postsave(String name, String password) { boolean flag = false; HttpURLConnection conn = null; try { URL url = new URL("https://10.20.90.3:8080/Register/ManageServlet?"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //post請求參數 String data = "name="+name+"&password="+password; OutputStream out = conn.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); // conn.setRequestProperty("Content-Length", 500);// 內容長度設置為500;請求頭消息格式設置 int respon = conn.getResponseCode(); if(respon == 200){ InputStream is = conn.getInputStream(); String stu = getStringFromInputStream(is); if(stu.equals("登錄成功")){ flag = true; } } } catch (Exception e) { e.printStackTrace(); }finally{ if(conn != null){ conn.disconnect(); } } return flag; } //解析服務返回的請求 private static String getStringFromInputStream(InputStream is) throws Exception{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024*8]; int len = -1; while((len = is.read(buffer)) != -1){ baos.write(buffer, 0, len); } is.close(); String html = new String(baos.toByteArray(), "GBK");//接收伺服器端的資料時,防止出現中文亂碼。 //String html = baos.toString(); baos.close(); return html; } }
兩者的差異很直觀:GET 把參數拼在網址後面,需要先用 URLEncoder 編碼處理中文;POST 則把參數寫進輸出流。兩種方式都設了連線與讀取逾時,並在 finally 中 disconnect,養成好習慣可以避免連線洩漏。回應文字解析時指定 GBK 編碼,是為了避免中文變亂碼。
好了結束了,內容簡單,大家自行了解吧。新手學習,高手交流。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持本站!
仿今日頭條 ViewPager 指示器:讓 Tab 文字隨滑動漸變填色
效果與思路 目標是做出那種切換 ViewPager 頁面時,頂部 Tab 文字顏色「逐漸染色」的效果。 一開始會直覺想「能不能只畫半個字」,但字元是無法切割繪製的。換個
Android 自訂縮放式側滑菜單完整實作
前言 剛接觸 Android 時,我對側滑菜單非常感興趣,也很好奇它的實作原理。隨著技術不斷精進,我也能自己封裝側滑菜單了。網路上雖有眾多現成方案,但本著學習與分享的精神
Android 異步消息處理機制詳解:從示例到 Handler 源碼剖析
最近事情不多,養病期間索性把之前零散積累的知識點整理成文,既方便自己複習,也希望能幫到別人。 一、為什麼要談這個話題 選這個題目有三個原因:一是在 GitHub 上看到有
Android Support Design 完全解析(七):CoordinatorLayout 與 Behavior
概述 前面我們簡單接觸過 CoordinatorLayout,本篇將深入剖析這個 ASD(Android Support Design)庫中最重要、也最強大的控件。回想一