使用Okhttp3
进行联网请求,通过post
方法把用户名和密码发送到服务进行校验,使用Gson
解析返回的json数据验证正确后,返回一个token值,并token值,username,password通过SharedPreferences
保存到本地,如下:
一、【Android项目实战 | 从零开始写app(一)】 创建项目
二、【Android项目实战 | 从零开始写app(二)】实现闪屏页,启动app
三、【Android项目实战 | 从零开始写app(三)】实现引导页,进入登录or主页面
四、【Android项目实战 | 从零开始写app(四)】Okhttp+Gson实现服务端登录验证功能
五、【Android项目实战 | 从零开始写app(五)】okhttp+gson实现服务端注册功能
六、【Android项目实战 | 从零开始写app(六)】用TabLayout+ViewPager搭建App 框架主页面底部导航栏
七、【Android项目实战 | 从零开始写app(七)】优化主页导航栏,禁用主页页面滑动切换效果
八、【Android项目实战 | 从零开始写app(八)】实现app首页广告轮播图切换和搜索跳转
九、【Android项目实战 | 从零开始写app(九)】实现主页底部新闻模块数据的解析
十、【Android项目实战 | 从零开始写app(10)】Okhttp+glide+json+ListView实现新闻模块数据的填充显示
十一、【Android项目实战 | 从零开始写app(11)】实现app首页九宫格服务分类点击跳转
十二、【Android项目实战 | 从零开始写app(12)】实现app首页热门推荐
十三、【Android项目实战 | 从零开始写app(13)】实现服务页面数据的解析
十四、【Android项目实战 | 从零开始写app(14)】实现用户中心模块清除token退出登录&信息修改等功能
十五、【Android项目实战 | 从零开始写app(15)】实现发布模块…
加载依赖:
注意在app目录下的build.gradle
加入如下依赖,接着Sync Now
同步一下:
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.github.bumptech.glide:glide:4.4.0'
联网配置:
在AndroidManifest清单文件中添加如下配置:
android:usesCleartextTraffic="true"
权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
还有另一种方式配置,但个人喜欢这种,简单方便。
package com.example.myapp.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.myapp.MainActivity;
import com.example.myapp.R;
import com.example.myapp.bean.LoginBean;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edt_name;
private EditText edt_psw;
private Button btn_login;
private Button btn_register;
private String token;
private int code;
private Intent intent = null;
Handler handler = new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg==obtainMessage()) {
Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_LONG).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
initView();
}
private void initView() {
edt_name = (EditText) findViewById(R.id.edt_name);
edt_psw = (EditText) findViewById(R.id.edt_psw);
btn_login = (Button) findViewById(R.id.btn_login);
btn_register = (Button) findViewById(R.id.btn_register);
btn_login.setOnClickListener(this);
btn_register.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
Login();
break;
case R.id.btn_register:
intent = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(intent);
break;
}
}
private void Login() {
final String username = edt_name.getText().toString().trim();
final String password = edt_psw.getText().toString().trim();
if (TextUtils.isEmpty(username )) {
Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
return;
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
return;
} else if (true) {
OkHttpClient client = new OkHttpClient();
final JSONObject jsonObject = new JSONObject();
try {
//提交的参数
jsonObject.put("username",username);
jsonObject.put("password",password);
} catch (JSONException e) {
e.printStackTrace();
}
MediaType mMediaType = MediaType.parse("application/json; charset=utf-8");
final RequestBody requestBody = RequestBody.create(mMediaType, jsonObject.toString());
Request request = new Request.Builder()
.post(requestBody)
.url("http://192.168.196.45:8080/login")
.build();
okhttp3.Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败
Log.i("请求情况:", "请求失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i("响应状态", "响应成功");
final String loginBody = response.body().string();
Gson gson = new Gson();
LoginBean loginBean = gson.fromJson(loginBody, LoginBean.class);
String loginResultCode = loginBean.getCode();
Log.i("返回状态码", loginResultCode);
//响应成功,判断状态码
if (loginResultCode.equals("200")) {
Log.i("登录状态", "登录成功");
//获取token
token = loginBean.getToken();
// 把token保存到本地
SharedPreferences.Editor editor= getSharedPreferences("get_token", MODE_PRIVATE).edit();
editor.putString("token",token);
editor.putString("username",username);
editor.putString("password",password);
editor.apply();
//保存token
//登录成功,跳到主界面
Message message = handler.obtainMessage();
message.obj = token;
handler.sendMessage(message);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),loginBody,Toast.LENGTH_LONG).show();
}
});
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"登录失败",Toast.LENGTH_LONG).show();
}
});
}
}
}
});
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#8ABFE8"
tools:context=".activity.LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="用户登录"
android:layout_marginTop="50dp"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="#fff"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
android:background="@drawable/shape_login_form"
android:gravity="center"
android:orientation="vertical"
android:paddingLeft="43dp"
android:paddingRight="31dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@mipmap/user1" />
<EditText
android:id="@+id/edt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@null"
android:hint="请输入用户名"
android:textColor="#000000"
android:text="liyingxia"
android:textColorHint="#bcbcbc"
android:textSize="18sp" />
LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="23dp"
android:layout_marginBottom="23dp"
android:background="#e8e7e7" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@mipmap/psw" />
<EditText
android:id="@+id/edt_psw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="@null"
android:text="123456"
android:inputType="textPassword"
android:hint="请输入密码"
android:textColor="#000000"
android:textColorHint="#bcbcbc"
android:textSize="18sp" />
LinearLayout>
LinearLayout>
<LinearLayout
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="@+id/btn_login"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:text="登录"
android:textColor="#ffffff"
android:layout_marginLeft="50dp"
android:background="@drawable/shape_login_btn"
android:textSize="20sp" />
<Button
android:id="@+id/btn_register"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="40dp"
android:layout_marginRight="50dp"
android:background="@drawable/shape_register_btn"
android:layout_alignParentRight="true"
android:text="注册"
android:textColor="#136BC8"
android:textSize="20sp" />
LinearLayout>
LinearLayout>
RelativeLayout>
由于为美化页面,在drawable目录下新建:shape_register_btn.xml,shape_login_btn.xml,shape_login_form.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="9dp" />
<solid android:color="#FFFFFF" />
shape>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="9dp" />
<solid android:color="#1276E1" />
shape>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="rectangle"
android:useLevel="false">
<solid android:color="#ffffff" />
<corners android:radius="10dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
shape>
item>
layer-list>
package com.example.myapp.bean;
/**
* @ProjectName: MyApp
* @Package: com.example.myapp.bean
* @ClassName: LoginBean
* @Description:
* @Author: liyingxia
* @CreateDate: 2021/4/13 16:50
*/
public class LoginBean {
/**
* msg : 操作成功
* code : 200
* token : eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImMyYjE1YTNkLTlkNWQtNGFmZi04MGU3LTNlNWMxYTdkYzcyNSJ9.sZxcMsSvH7F50jCpTdtrv296mgq5IOI8OAo8rAXDQ4mw7KssvPsdwFcFdxHyGodfYmrsDxv0wyyEgDdl7JDxoQ
*/
private String msg;
private String code;
private String token;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public LoginBean(String msg, String code, String token) {
this.msg = msg;
this.code = code;
this.token = token;
}
@Override
public String toString() {
return "UserLogin{" +
"msg='" + msg + '\'' +
", code=" + code +
", token='" + token + '\'' +
'}';
}
}