当前位置:   article > 正文

Android开发,实现和后端接口交互,调用!_android如何与后端对接

android如何与后端对接

创建一个空的Android项目

在这里插入图片描述

  • 创建成功之后在MainActivity中实现调用JavaSpring后端的接口项目,这里使用的是,实现点击一个按钮,然后发送http请求的示例
  • 准备工作:Android自带的http发送请求的方法不太好用,所以我们使用okhttp方法来实现,打开,buile.gradle(Module:app),导入下面的代码
apply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    buildToolsVersion "33.0.0"
    defaultConfig {
        applicationId "com.skypan.myapplication"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.squareup.okhttp3:okhttp:4.4.1'//导入这个,然后点击刷新下载,成功之后就可以使用了
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
  • 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
  • 首先是实现后端使用@RequestBody注解开发的接口
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //发送java 中@RequestBody注解的请求示例
        Button button = findViewById(R.id.按钮id);
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //调用后端接口
                            String json = "json格式的body";//后端接收的body参数
							 //发送请求,可以使用默认的http,这里使用okhttp请求
                            OkHttpClient client = new OkHttpClient();//创建client对象
                            //发送请求
                            Request request = new Request.Builder()
                                    .url("接口地址")
                                    .post(
                                            RequestBody
                                                    .create(
                                                    MediaType
                                                            .parse("application/json"),json))
                                    .build();
                            Response response = client.newCall(request).execute();//执行发送的指令,并接收后端接口返回的数据
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                	//操作安卓界面不能在单线程中,只能在主线程中,所以使用runOnUiThread中操作ui
                                    Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
  • 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
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 调用JavaSpring开发的参数直接放在url上的请求示例
Button button1 = findViewById(R.id.按钮id);
        button1.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //调用后端接口,设置参数
                        FormBody.Builder params = new FormBody.Builder();
                        params.add("参数名称","参数值");

                        //发送请求,可以使用默认的http,这里使用okhttp请求
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url("接口地址")
                                .post(params.build())
                                .build();
                        Response response = client.newCall(request).execute();//执行发送的指令
                        //获取返回过来的参数
                        String responseData = response.body().string();//获取返回过来的json格式结果
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.get("参数名称");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }catch (Exception e){
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }).start();
        }
    });
  • 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
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 调用JavaSpring后端开发的上传文件的接口示例
Button button2 = findViewById(R.id.按钮id);
        button2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //调用后端接口
                            OkHttpClient client = new OkHttpClient();
                            File file = new File("文件路径");//被上传的文件,注意权限
                            MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);//通过表单上传
                            RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"),file);//上传的文件以及类型
                            requestBody.addFormDataPart("file",file.getName(),fileBody);//参数:1请求的key,2.文件名称,3fileBody
                            final Request request = new Request.Builder()
                                    .url("接口地址")
                                    .post(requestBody.build())
                                    .build();//创建请求
                            client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                    e.printStackTrace();
                                    Log.d("文件上传","失败了");
                                }

                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    if (response.isSuccessful()){
                                        try {
                                            JSONObject jsonObject = new JSONObject(response.body().string());
                                            Log.d("文件上传成功",jsonObject.getString("code"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }else {
                                        Log.d("文件上传",response.message()+"error:body"+response.body().string());
                                    }
                                }
                            });
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
  • 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
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/264925?site
推荐阅读
相关标签
  

闽ICP备14008679号