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;
    }

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

相关推荐
桦说编程20 分钟前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅2 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者3 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺3 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart4 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP5 小时前
MyBatis-mybatis入门与增删改查
java
孟陬9 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌9 小时前
一站式了解四种限流算法
java·后端·go
华仔啊9 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java