使用okHttp登录、Md5密码加密
使用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.,");
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是本章的登录