Android使⽤OKhttp3实现登录注册功能+springboot搭建后端的详细过程⽬录
⼀、Android前端实现
⼆、数据库
三、SpringBoot后端搭建
四、部署⾄服务器
五、运⾏测试
⼀、Android前端实现
新建⼀个login的项⽬,主要的⼏个⽂件在这⾥
1、gradle引⼊OKhttp3依赖
implementation 'com.squareup.okhttp3:okhttp:3.14.7'
implementation 'com.squareup.okio:okio:1.17.5'
2、l布局⽂件
<?xml version="1.0" encoding="utf-8"?>
&straintlayout.widget.ConstraintLayout xmlns:android="schemas.android/apk/res/android"
xmlns:app="schemas.android/apk/res-auto"
xmlns:tools="schemas.android/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="⽤户名"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.051" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="密码"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/username"
app:layout_constraintVertical_bias="0.067" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="register"
android:text="注册"
android:textSize="24sp"
app:backgroundTint="#E91E63"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/password"
app:layout_constraintVertical_bias="0.058" />
<Button
android:id="@+id/getUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="getUser"
android:text="获取"
android:textSize="24sp"
app:backgroundTint="#E91E63"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button3"
app:layout_constraintVertical_bias="0.174" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登录"
android:textSize="24sp"
app:backgroundTint="#E91E63"
android:onClick="login"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
app:layout_constraintVertical_bias="0.113" />
</straintlayout.widget.ConstraintLayout>
3、l配置⽂件
这⾥需要加上⽹络请求权限,添加⽹络权限的时候注意:在res⽬录下新建xml⽬录,创建network_l⽂件
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
并在配置⽂件中加⼊这⾏代码:
android:networkSecurityConfig="@xml/network_security_config"
完整的l⽂件如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="schemas.android/apk/res/android"
package="ample.login">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/Theme.Login">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
4、创建User实体类
新建entity⽬录创建User实体类。注意这⾥我是根据后端数据库的字段创建的,在实现登录注册的时候只需要id,username,password ⼏个基础的字段就⾏,这⾥我⽐较多,读者可以⾃⾏忽略。User.java
ity;
public class User {
private Integer userId;
private String userName;
private String userPassword;
private String currentVersion;
private String latestVersion;
private String updateDescription;
private String headPortrait;
private String nickName;
private String vipTime;
private String userCategory;
private String registerDate;
public User(Integer userId, String userName, String userPassword, String currentVersion, String latestVersion, String updateDescription, String headPortrait, String nickName, String vipTime, String userCategory, String registerDate) { this.userId = userId;
this.userName = userName;
this.userPassword = userPassword;
this.currentVersion = currentVersion;
this.latestVersion = latestVersion;
this.updateDescription = updateDescription;
this.headPortrait = headPortrait;
this.nickName = nickName;
this.vipTime = vipTime;
this.userCategory = userCategory;
}
public User() {
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getCurrentVersion() {
return currentVersion;
}
public void setCurrentVersion(String currentVersion) {
this.currentVersion = currentVersion;
}
public String getLatestVersion() {
return latestVersion;
}
public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}
public String getUpdateDescription() {
return updateDescription;
}
public void setUpdateDescription(String updateDescription) { this.updateDescription = updateDescription;
}
public String getHeadPortrait() {
return headPortrait;
}
public void setHeadPortrait(String headPortrait) {
this.headPortrait = headPortrait;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getVipTime() {
return vipTime;
}
public void setVipTime(String vipTime) {
this.vipTime = vipTime;
}
public String getUserCategory() {
return userCategory;
}
public void setUserCategory(String userCategory) {
this.userCategory = userCategory;
}
public String getRegisterDate() {
return registerDate;
}
public void setRegisterDate(String registerDate) {
}
}
LoginUser.java
public class LoginUser {
private String userName;
private String userPassword;
public LoginUser(String userName, String userPassword) { this.userName = userName;
this.userPassword = userPassword;
}
public LoginUser() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
安卓intent用法public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
5、MainActivity.java
ample.login;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
ity.User;
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 MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
}
public void register(View view) {
user = new User();
user.Text().toString());
user.Text().toString());
Log.d("whqusername",Text().toString());
Log.d("whqpassword",Text().toString());
new Thread(new Runnable() {
@Override
public void run() {
MediaType JSON = MediaType.parse("application/json;charset=utf-8");
JSONObject jsonObject = new JSONObject();
OkHttpClient httpClient = new OkHttpClient();
try {
jsonObject.put("userId",10);
jsonObject.put("userName",UserName());
jsonObject.put("userPassword",UserPassword());
jsonObject.put("currentVersion",null);
jsonObject.put("latestVersion",null);
jsonObject.put("updateDescription",null);
jsonObject.put("headPortrait",null);
jsonObject.put("nickName",UserName());
jsonObject.put("vipTime",null);
jsonObject.put("userCategory",null);
jsonObject.put("registerDate",null);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = ate(JSON, String.valueOf(jsonObject)); String url = "ip:8001/server/user/addUser/";
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = wCall(request);
@Override
public void onFailure(Call call, IOException e) {
Log.d("whq","失败了");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("whq",String()+"------------------");
Log.d("whq",response.body().toString()+"------------------");
}
});
}
}).start();
}
public void getUser(View view) {
OkHttpClient httpClient = new OkHttpClient();
String url = "ip:8001/server/user/getAllUserName";
Request getRequest = new Request.Builder()
.url(url)
.
get()
.build();
Call call = wCall(getRequest);
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步请求,要放到⼦线程执⾏
Response response = ute();
Log.i("whq+getAllUserName", "okHttpGet run: response:"+ response.body().string()); } catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void login(View view) {
loginUser = new LoginUser();
loginUser.Text().toString());
loginUser.Text().toString());
new Thread(new Runnable() {
@Override
public void run() {
MediaType JSON = MediaType.parse("application/json;charset=utf-8");
JSONObject jsonObject = new JSONObject();
OkHttpClient httpClient = new OkHttpClient();
try {
jsonObject.put("userName",UserName());
jsonObject.put("userPassword",UserPassword()));
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = ate(JSON, String.valueOf(jsonObject)); String url = "ip:8001/server/user/login";
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = wCall(request);
@Override
public void onFailure(Call call, IOException e) {
Log.d("whq登录","失败了");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String MyResult = response.body().string();
Log.d("whq登录",response+"---------response---------");
Log.d("whq登录",ssage()+"---------message---------");
Log.d("whq登录",response.body().toString()+"------------------");
Log.d("whq登录",MyResult+"-----------MyResult-------");
}
});
}
}).start();
}
}
到这⾥就实现了Android的前端实现。
⼆、数据库
数据库就是简单的⼀个user表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`userPassword` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`currentVersion` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`latestVersion` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`updateDescription` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`headPortrait` mediumblob NULL,
`nickName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`vipTime` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`userCategory` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT 'normal',
`registerDate` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`userId`, `userName`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC; SET FOREIGN_KEY_CHECKS = 1;
三、SpringBoot后端搭建
后端搭建⽤到的是SSM框架
1、新建⼀个springboot项⽬,添加依赖
<properties>
<java.version>1.8</java.version>
<mybatis-plus.version>3.0.5</mybatis-plus.version>
<swagger.version>2.7.0</swagger.version>
<jodatime.version>2.10.1</jodatime.version>
<poi.version>3.17</poi.version>
<httpclient.version>4.5.1</httpclient.version>
<gson.version>2.8.2</gson.version>
<velocity.version>2.0</velocity.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Spring Cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--mybatis-plus 持久层-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- velocity 模板引擎, Mybatis Plus 代码⽣成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--⽇期时间⼯具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok⽤来简化实体类:需要安装lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论