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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理