Android的簡單前后端交互(okHttp+springboot+mysql)
前言
前陣子發(fā)現(xiàn)了個有意思又好用的框架——okHttp。由于課程設計需要,無意間發(fā)現(xiàn)了這個框架,打算利用此框架與后端交互,可以參考前后端分離的項目,把android當做前端,springboot當做后端,以下是二者的簡單交互。
okHttp說明
(1)android網(wǎng)絡框架之OKhttp
一個處理網(wǎng)絡請求的開源項目,是安卓端最火熱的輕量級框架,由移動支付Square公司貢獻(該公司還貢獻了Picasso)
用于替代HttpUrlConnection和Apache HttpClient
(2)okHttp優(yōu)勢
允許連接到同一個主機地址的所有請求,提高請求效率
共享Socket,減少對服務器的請求次數(shù)
通過連接池,減少了請求延遲
緩存響應數(shù)據(jù)來減少重復的網(wǎng)絡請求
減少了對數(shù)據(jù)流量的消耗
自動處理GZip壓縮
(3)OKhttp的功能
get,post請求
文件的上傳下載
加載圖片(內(nèi)部會圖片大小自動壓縮)
支持請求回調(diào),直接返回對象、對象集合
支持session的保持
android前端
邏輯控制:LoginActivity.java
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.TextView;
import com.campus.book.R;
import com.campus.book.entity.User;
import com.campus.book.util.http.OKHttpUtil;
import com.google.gson.Gson;
public class LoginActivity extends AppCompatActivity {
//這個url可以通過cmd中輸入 ipconfig IPv4 地址即為本地電腦的地址 8081為后端的端口號
private String baseUrl="http://192.168.xxx.1:8081";
private TextView tv=null;
EditText userId = null;
EditText pwd = null ;
Button login=null;
private Button registry=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
setTitle("登錄");
tv=findViewById(R.id.tv);
login = (Button)findViewById(R.id.login);
registry = (Button)findViewById(R.id.registry);
userId=(EditText) findViewById(R.id.userId);
pwd=findViewById(R.id.pwd);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id = userId.getText().toString();
String password=pwd.getText().toString();
User user=new User(id,password);
Gson gson=new Gson();
String json=gson.toJson(user);
String args[]=new String[]{"user","login"};
String res= OKHttpUtil.postSyncRequest(baseUrl,json,args);
Log.d("同步:",res);
res= OKHttpUtil.postAsyncRequest(baseUrl,json,args);
Log.d("異步:",res);
}
});
registry.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String args[]=new String[]{"user","getUser","123"};
String res= OKHttpUtil.getSyncRequest(baseUrl,args);
System.out.println("同步:"+res);
String args1[]=new String[]{"user","getUser","123"};
res= OKHttpUtil.getAsyncRequest(baseUrl,args1);
System.out.println("異步:"+res);
}
});
}
}
布局方式:activity_login.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv"
android:text="內(nèi)容:"/>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/mainBg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/login" />
<!--@drawable/login改成相應的背景圖-->
<TableLayout
android:layout_width="350dp"
android:layout_height="match_parent"
android:stretchColumns="*"
android:layout_marginBottom="150sp"
android:layout_gravity="center" >
<TableRow android:layout_height="match_parent">
<EditText
android:id="@+id/userId"
android:layout_column="0"
android:layout_span="2"
android:hint="請輸入手機號"
android:textColorHint="#FFFFFF"
android:textColor="#FFFFFF"
android:textCursorDrawable="@drawable/cursor_color"
android:textSize="15sp" />
</TableRow>
<TableRow android:layout_height="match_parent" >
<EditText
android:id="@+id/pwd"
android:inputType="textPassword"
android:layout_column="0"
android:layout_span="2"
android:hint="請輸入密碼"
android:textColorHint="#FFFFFF"
android:textColor="#FFFFFF"
android:textCursorDrawable="@drawable/cursor_color"
android:textSize="15sp" />
</TableRow>
<TableRow android:layout_height="match_parent">
<Button
android:id="@+id/login"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:background="#000000"
android:layout_margin="8dp"
android:textSize="15sp"
android:text="登錄" />
<Button
android:id="@+id/registry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:background="#000000"
android:layout_margin="8dp"
android:textSize="15sp"
android:text="注冊" />
</TableRow>
</TableLayout>
</FrameLayout>
</LinearLayout>
其中,cursor_color.xml在drawable中。
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<size android:width="2dp" />
<solid android:color="@android:color/black" />
</shape>
springboot+mysql后端
(1)數(shù)據(jù)庫
表user

(2)springboot中的controller層
如何搭建springboot工程就不再贅述了(如有需要,可留言,后續(xù)可發(fā)搭建教程),可自行參考其他文章。
@RestController
@RequestMapping("http://user")
public class UserController {
@Autowired
private UserService userService;
//Gson gson= JsonBean.getGson();
static Gson gson=new GsonBuilder().serializeNulls().create();
@GetMapping("/list")
public List<User> list() {
return this.userService.list();
}
@PostMapping("/login")
public User login(String json){
User result=null;
User user=null;
User user1=null;
try{
user=gson.fromJson(json,User.class);
}catch (Exception e){
e.printStackTrace();
}
user1=userService.getById(user.getUserId());
if(user1!=null){//存在該賬戶
if(user1.getPassword().equals(user.getPassword())){//密碼正確
result=user1;
}else{//密碼錯誤
}
}else{//不存在該賬戶
}
return result;
}
@GetMapping("/getUser/{id}")
public User getUser(@PathVariable("id") Serializable id){
User user=userService.getById(id);
if(user!=null){//存在
}else{//不存在
}
return user;
}
}
運行(交互)效果

(1)點擊“登錄”按鈕,發(fā)起post請求
android端

后端

(2)點擊“注冊”按鈕發(fā)起get請求
android端

后端

這樣就達到了前后端分離的效果,是不是很神奇!可以愉快的和小組成員分開進行開發(fā)啦!
在Android端中用到了個人結合需要編寫的okHttp的工具類,可參考上篇文章:okHttp的get和post請求的簡單封裝與使用
到此這篇關于Android的簡單前后端交互(okHttp+springboot+mysql)的文章就介紹到這了,更多相關Android 前后端交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android編程實現(xiàn)仿優(yōu)酷旋轉菜單效果(附demo源碼)
這篇文章主要介紹了Android編程實現(xiàn)仿優(yōu)酷旋轉菜單效果的方法,較為詳細的分析了Android實現(xiàn)旋轉菜單的布局與功能實現(xiàn)技巧,并附帶完整的demo源碼供讀者下載參考,需要的朋友可以參考下2015-12-12
如何判斷軟件程序是否聯(lián)網(wǎng) 聯(lián)網(wǎng)狀態(tài)提示信息Android實現(xiàn)
這篇文章主要為大家詳細介紹了如何判斷軟件程序是否聯(lián)網(wǎng)的實現(xiàn)代碼,Android實現(xiàn)聯(lián)網(wǎng)狀態(tài)信息提示,感興趣的小伙伴們可以參考一下2016-05-05
Android之自定義實現(xiàn)BaseAdapter(通用適配器三)
這篇文章主要為大家詳細介紹了Android之自定義實現(xiàn)BaseAdapter通用適配器第三篇,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-12-12
Kotlin文件讀寫與SharedPreferences存儲功能實現(xiàn)方法
SharedPreferences是安卓平臺上一個輕量級的存儲類,用來保存應用的一些常用配置,比如Activity狀態(tài),Activity暫停時,將此activity的狀態(tài)保存到SharedPereferences中;當Activity重載,系統(tǒng)回調(diào)方法onSaveInstanceState時,再從SharedPreferences中將值取出2022-12-12
Android進度條ProgressBar的實現(xiàn)代碼
這篇文章主要為大家詳細介紹了Android進度條ProgressBar的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09

