随笔 - 403  文章 - 0  评论 - 6  阅读 - 3254

2024年3月26日如何放松post和get请求连接远程数据库

android连接远程数据库

首先要在build.gradle.kt引入配置文件

implementation("com.google.code.gson:gson:2.10")
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation ("com.squareup.retrofit2:retrofit:2.9.0")
    implementation ("com.squareup.retrofit2:converter-gson:2.9.0")

然后是post的发送

复制代码
  private void postJson() {
        String jsonString = "";
        User user = new User();
        String username = et_username.getText().toString();
        String password = et_password.getText().toString();
        // 输出未被包装的用户信息
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userid", et_userid.getText().toString());
            jsonObject.put("password", password);
            jsonObject.put("username", username);
            jsonObject.put("phone", et_phone.getText().toString());
            jsonObject.put("identity", et_identity.getText().toString());
            jsonObject.put("grade", et_grade.getText().toString());
            jsonString = jsonObject.toString();
            System.out.println("JSON to be sent: " + jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建一个POST方式的请求结构
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonString, mediaType);
        OkHttpClient client = new OkHttpClient(); // 创建一个okhttp客户端对象
        Request request = new Request.Builder().post(body).url(URL_REGISTER).build();//URL_REGISER是本机地址和发送网址。
        Call call = client.newCall(request); // 根据请求结构创建调用对象
        // 加入HTTP请求队列。异步调用,并设置接口应答的回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) { // 请求失败
                // 回到主线程操纵界面
                runOnUiThread(() -> Toastutil.showMsg(RegisterActivity.this,"注册失败"));
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException { // 请求成功
                String resp = response.body().string();
                // 回到主线程操纵界面
                runOnUiThread(() -> Toastutil.showMsg(RegisterActivity.this,"注册成功"));
            }
        });
    }
复制代码

使用retrofit封装的学习网站如下Retrofit2 实战(一、使用详解篇) - 掘金 (juejin.cn)

posted on   石铁生  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示