Android与后端通信(Android向后端发送请求获取数据)

参考视频:https://www.bilibili.com/video/BV1mQ4y1A7GV

0、注意点

1、向后端发起请求,要new一个线程

new Thread(new Runnable() {
    @Override
    public void run() {
        
    }
}).start();

2、在子线程内想要在UI上显示内容或弹框提示,需要这么写

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(MainActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
    }
});

3、在build.gradle(Module)中添加

implementation 'com.squareup.okhttp3:okhttp:4.4.1'

4、在mainfest中添加网络权限

<uses-permission android:name="android.permission.INTERNET" />

1、@RequestBody

Constants.IP 是后端的IP 加上端口号,我写在Constans类中了,同一台电脑就是局域网地址
例如

http://192.168.100.105:8081
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //向后端发起请求
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.i("username", String.valueOf(userName.getText()));
                            Log.i("password", String.valueOf(passWord.getText()));
                            if(userName.getText() == null || passWord.getText() == null){
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this,"用户名或密码未填写",Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                            String json = "{\n" +
                                    "    \"username\":\""+userName.getText()+"\",\n" +
                                    "    \"password\":\""+passWord.getText()+"\"\n" +
                                    "}";
                            //创建http客户端
                            OkHttpClient client = new OkHttpClient();
                            //创建http请求
                            Request request = new Request.Builder()
                                    .url(Constants.IP+"/user/login")
                                    .post(RequestBody.create(MediaType.parse("application/json"),json))
                                    .build();
                            Response response = client.newCall(request).execute();//执行
                            String res = response.body().string();
                            JSONObject jsonObject = new JSONObject(res);
                            int code = jsonObject.getInt("code");
                            String msg = jsonObject.getString("msg");
                            String data = jsonObject.getString("data");
                            JSONObject jsonObject1;
                            if(code == 200){
                                jsonObject1 = new JSONObject(data);
                            }else{

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
                                    }
                                });
                                return;
                            }

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
                                    if(code == 200) {
                                        Intent intent = new Intent(MainActivity.this, NavActivity.class);
                                        startActivity(intent);
                                    }
                                }
                            });
                        }catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this,Constants.NETERR,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });

2、@RequestParam

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            FormBody.Builder params = new FormBody.Builder();
            params.add("className",userInfo.getClassname());
            params.add("expense",editText.getText().toString());
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(Constants.IP+"/class/updateExpense")
                    .post(params.build())
                    .build();
            Response response = client.newCall(request).execute();//执行发送的指令

            classExpense.setText("   班费:" + editText.getText().toString());
            Log.i("expense",expense+"");
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getActivity(),Constants.NETERR,Toast.LENGTH_SHORT).show();
        }
    }
}).start();

3、file 类型(如图片、视频)

sendPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { //上传文件
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            //发送POST请求给后端
                            OkHttpClient client = new OkHttpClient(); //创建http客户端
                            File file = new File("/sdcard/Movies/abcd.mp4"); //需要被上传的文件,小心权限问题
                            MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
                            RequestBody fileBody = RequestBody.create(MediaType.parse("video/*"), file);//上传的文件以及类型, image或者video
                            requestBody.addFormDataPart("file", file.getName(), fileBody);// 参数:请求key,文件名称,RequestBody
                            Request request = new Request.Builder()
                                    .url(Api.url + "/comment/upload_img")
                                    .post(requestBody.build())
                                    .build();
                            client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
                                @Override    // readTimeout("请求超时时间" , 时间单位);
                                public void onFailure(Call call, IOException e) {
                                    Log.d("文件上传", "失败了");
                                    e.printStackTrace();
                                }
                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    if (response.isSuccessful()) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response.body().string());
                                            Log.d("文件上传成功",jsonObject.getInt("code")+"");
                                            Log.d("服务器上的文件名", jsonObject.getString("body"));
                                        }catch (Exception e){
                                            e.printStackTrace();
                                        }
                                    } else {
                                        Log.d("文件上传", response.message() + " error : body " + response.body().string());
                                    }
                                }
                            });
                            //获取后端回复过来的返回值(如果有的话)
                            runOnUiThread(new Runnable() { //操作UI,更新界面
                                @Override
                                public void run() {
                                    sendPost.setText("请求已发送!");
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(POST.this,"网络连接失败!",Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值