android将json数据传递到后端springboot

引入依赖:

build.gradle.kts

复制代码
    implementation ("com.squareup.okhttp3:okhttp:4.11.0")
    implementation ("com.google.code.gson:gson:2.10.1")

androidMainfest.xml文件配置

http明文允许:

复制代码
<application

...
    android:usesCleartextTraffic="true"

允许网络连接:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:an  ...
    <uses-permission android:name="android.permission.INTERNET"/>

  

页面代码:

xml

复制代码
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="24dp"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etUsername"
        android:hint="用户名"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/etPassword"
        android:hint="密码"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btnRegister"
        android:text="注册"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"/>

    <TextView
        android:id="@+id/tvResult"
        android:text=""
        android:textColor="#FF0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"/>
</LinearLayout>

java代码:

复制代码
package com.example.demo3.register;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.demo3.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class register extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private Button btnRegister;
    private TextView tvResult;

    private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private static final String BASE_URL = "http://10.0.2.2:8080"; // 替换为后端地址
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);



        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnRegister = findViewById(R.id.btnRegister);
        tvResult = findViewById(R.id.tvResult);

        btnRegister.setOnClickListener(v -> registerUser());


    }

    private void registerUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 构建请求体 JSON
        User user = new User(username, password);
        String json = gson.toJson(user);
        RequestBody body = RequestBody.create(json, JSON);

        // 构建请求
        Request request = new Request.Builder()
                .url(BASE_URL + "/api/register")
                .post(body)
                .build();

        // 异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> tvResult.setText("请求失败: " + e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body() != null) {
                    String resStr = response.body().string();
                    Map<String, Object> resMap = gson.fromJson(resStr, Map.class);
                    runOnUiThread(() -> {
                        tvResult.setText(resMap.get("message").toString());
                    });
                }
            }
        });
    }

    // 用户类与后端一致
    static class User {

        private String username;
        private String password;

        public User(String username, String password) {
            this.username = username;
            this.password = password;
        }

        // Getter/Setter 可选


        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

    }

}

在上面的代码中获取后端返回的数据的代码是:

在下面的代码返回的后端数据库数据,

效果是

如果是上图的语句

复制代码
Log.d("response", String.valueOf(response));

则打印出来的是

配置:

使用子包跳转页面时

后端接口的编写:

复制代码
 @Autowired
    private UserRepository userRepository;

    // 注册接口
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            response.put("code", 400);
            response.put("message", "用户名已存在");
            return response;
        }

        // 保存到数据库
        userRepository.save(user);

        response.put("code", 200);
        response.put("message", "注册成功");
        return response;
    }

欢迎关注微信公众号,码文狙击所

相关推荐
逑之1 天前
C语言笔记13:数据在内存中的存储
c语言·开发语言·笔记
不会c嘎嘎1 天前
QT中的常用控件 (四)
开发语言·qt
bing.shao1 天前
AI在电商上架图片领域的应用
开发语言·人工智能·golang
步步为营DotNet1 天前
深度探索.NET 中ValueTask:优化异步性能的轻量级利器
java·spring·.net
栈与堆1 天前
LeetCode-88-合并两个有序数组
java·开发语言·数据结构·python·算法·leetcode·rust
彩妙不是菜喵1 天前
C++:类与对象
开发语言·c++
董世昌411 天前
添加、删除、替换、插入元素的全方法指南
java·开发语言·前端
源代码•宸1 天前
Leetcode—712. 两个字符串的最小ASCII删除和【中等】
开发语言·后端·算法·leetcode·职场和发展·golang·dp
小当家.1051 天前
JVM八股详解(上部):核心原理与内存管理
java·jvm·学习·面试
heartbeat..1 天前
Spring 声明式事务:原理、使用及失效场景详解
java·spring·面试·事务