使用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是本章的登錄
