24.3.12
所花时间:上一天课,
代码量:400行
博客量:6
了解的知识点:Android studio 、IDEA和MySQL联合开发,安卓使用okhttp进行http请求,使用json的格式进行数据传输到IDEA的web服务器,由web服务器解析进行数据库新增操作:
实现代码:
安卓端
写在前面:安卓开发因为模拟器和电脑并不属于同一台机器,所以在进行网络请求提交时不能够以本机地址作为web接口,这里要使用cmd命令行ipconfig查看自己本机局域网ip后将提交的http请求提交到对应的接口,可以通过尝试从浏览器是否能够访问对应ip来判断是否正确
另外:高版本安卓因为安全性禁止了http请求的提交,这里需要重新设置一下网络策略:
首先在Manifest.xm文件添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
再设置一个网络策略
android:networkSecurityConfig="@xml/network_security_config"
之后再/res/xml目录下新建一个network_security_confih.xml文件并输入以下内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</base-config>
</network-security-config>
之后就可以提交http请求了
逻辑层代码
package com.example.classtest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
EditText et_classname;
EditText et_teacher;
EditText et_position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_classname = findViewById(R.id.et_classname);
et_teacher = findViewById(R.id.et_teacher);
et_position = findViewById(R.id.et_position);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String classname = et_classname.getText().toString();
String teacher = et_teacher.getText().toString();
String position = et_position.getText().toString();
if(StringUtils.isNotEmpty(classname)&&StringUtils.isNotEmpty(teacher)&&StringUtils.isNotEmpty(position)){
new Thread(new Runnable() {
@Override
public void run() {
String url = "http://10.99.115.57/add"; // 这里需要替换成你自己电脑局域网的ip地址
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
try {
json.put("classname", classname);
json.put("teacher", teacher);
json.put("position", position);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(json.toString(), okhttp3.MediaType.parse("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
// 注册失败,处理失败原因
e.printStackTrace();
// 处理注册失败后的逻辑
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 注册成功,处理响应结果
String responseData = response.body().string();
// 处理注册成功后的逻辑
if (responseData.equals("success")){
Looper.prepare();
Toast.makeText(MainActivity.this,"注册成功!",Toast.LENGTH_SHORT).show();
Looper.loop();
}else {
Looper.prepare();
Toast.makeText(MainActivity.this,"错误",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
});
}
}).start();
} else {
Toast.makeText(MainActivity.this,"请输入正确的信息",Toast.LENGTH_SHORT).show();
}
}
});
}
}
数据结构类
package com.example.classtest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class ClassInfo {
private String classname;
private String teacher;
private String position;
public ClassInfo(String classname, String teacher, String position) {
this.classname = classname;
this.teacher = teacher;
this.position = position;
}
// Getters and setters
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public String getTeacher() {
return teacher;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
// Static method to parse JSON string and create ClassInfo object
public static ClassInfo fromJsonString(String jsonString) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
String classname = jsonObject.getString("classname");
String teacher = jsonObject.getString("teacher");
String position = jsonObject.getString("position");
return new ClassInfo(classname, teacher, position);
}
}
页面布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<EditText
android:id="@+id/et_classname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="10dp"
android:hint="课程名称"
android:textColor="#ffbd27"
/>
<EditText
android:id="@+id/et_teacher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="10dp"
android:hint="任课教师"
android:textColor="#ffbd27"
/>
<EditText
android:id="@+id/et_position"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="10dp"
android:hint="上课地点"
android:textColor="#ffbd27"
/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:background="#00BCD4"
android:text="确认"
android:textColor="#333333"
android:textSize="20dp" />
</LinearLayout>
Web端
添加maven依赖项:
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
数据结构类
package org.test.classtest;
import org.json.JSONException;
import org.json.JSONObject;
public class Course {
private String className;
private String teacher;
private String position;
Course(String className, String teacher, String position){
this.className = className;
this.teacher = teacher;
this.position = position;
}
Course(){
}
String getClassName (){
return className;
}
String getTeacher() {
return teacher;
}
String getPosition() {
return position;
}
void setPosition(String position){
this.position = position;
}
void setClassName(String className){
this.className = className;
}
void setTeacher (String teacher){
this.teacher = teacher;
}
public static Course fromJsonString(String jsonString) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
String classname = jsonObject.getString("classname");
String teacher = jsonObject.getString("teacher");
String position = jsonObject.getString("position");
return new Course(classname, teacher, position);
}
}
添加接口
package org.test.classtest;
import org.json.JSONException;
import org.json.JSONObject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
@WebServlet("/add")
public class Add extends HttpServlet {
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 预检请求处理
setCorsHeaders(resp);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
setCorsHeaders(response);
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
DAO dao = new DAO();
System.out.println(request);
StringBuilder jsonRequest = new StringBuilder();
try (BufferedReader reader = request.getReader()) {
String line;
while ((line = reader.readLine()) != null) {
jsonRequest.append(line);
}
}
// 解析JSON数据
JSONObject jsonObject;
Course course;
try {
jsonObject = new JSONObject(jsonRequest.toString());
String classname = jsonObject.getString("classname");
String teacher = jsonObject.getString("teacher");
String position = jsonObject.getString("position");
course = new Course(classname, teacher, position);
System.out.println(course);
} catch (JSONException e) {
// JSON解析失败,返回错误响应
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.setContentType("application/json");
response.getWriter().write("{\"error\": \"Failed to parse JSON\"}");
return;
}
String AddQuery1 = "INSERT INTO course (classname, teacher,position) VALUES (?, ? , ? )";
int rowsInserted = dao.executeUpdate(AddQuery1, course.getClassName(), course.getTeacher(),course.getPosition());
if (rowsInserted > 0) {
System.out.println("INSERT SUCCESS");
String responseData = "success";
// 设置响应类型为JSON
response.setContentType("application/json");
// 将JSON响应发送回前端
response.getWriter().write(responseData);
} else {
System.out.println("INSERT ERROR");
String errorResponse = "error";
response.setContentType("application/json");
response.getWriter().write(errorResponse);
}
}
private void setCorsHeaders(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源访问
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的请求方法
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头
response.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的缓存时间,单位秒
}
}
数据库:记得换成自己的连接地址
这里附上创建数据库的语句:
CREATE TABLE course (
classname VARCHAR(255),
teacher VARCHAR(255),
position VARCHAR(255)
);
数据库封装代码:
package org.test.classtest;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DAO {
private static String url;
private static String username;
private static String password;
static {
// 从配置文件加载数据库连接信息
url = "jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8";
username = "test";
password = "123456";
// 注册数据库驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// 执行更新操作(插入、更新、删除)
public int executeUpdate(String sql, Object... params) {
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
// 设置SQL更新参数
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
return preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
// 关闭数据库连接和资源
public void closeResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}