Android-okhttp调接口传参简单举例

步骤1:在主线程中创建thread调接口

java 复制代码
        new Thread(new Runnable() {
            @Override
            public void run() {
                getServiceList();
            }
        }).start();

步骤2:okhttp调接口

java 复制代码
private void getServiceList(){
        Message msg = new Message();
        try{
            OkHttpClient okHttpClient = new OkHttpClient();

            
            FormBody.Builder formBodyBuilder = new FormBody.Builder();

            formBodyBuilder.add("token", "xxx")
                    .add("id", "idxxx");

            if (constellationArr != null) {
                for (String constellation : constellationArr) {
                    formBodyBuilder.add("constellationArr", constellation);
                }
            }

            FormBody formBody = formBodyBuilder.build();
            ///
            Request request = new Request.Builder()
                    .url("调接口url")
                    .post(formBody)
                    .build();

            // 创建 Call 对象并执行请求
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            // 处理响应
            if (response.isSuccessful()) {
                // 响应成功
                String responseBody = response.body().string();
                // 在这里处理响应体
                JSONObject jsonObject = new JSONObject(responseBody);

                boolean success = jsonObject.getBoolean("success");
                String message = jsonObject.getString("msg");
                String obj = jsonObject.getString("obj");
                Log.e(TAG, obj);
                if (success) {
                    // 使用 TypeToken 获取泛型类型
                    TypeToken<ArrayList<ServicePersonShortBean>> typeToken = new TypeToken<ArrayList<ServicePersonShortBean>>() {};
                    ArrayList<ServicePersonShortBean> servicePersonShortBeanList = gson.fromJson(obj, typeToken.getType());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("servicePersonShortBeanList", servicePersonShortBeanList);
                    msg.setData(bundle);
                    msg.what = 1;
                    handler.sendMessage(msg);

                } else {
                    Bundle bundle = new Bundle();
                    if(message.equals("token找不到")){
                        bundle.putString("message", "请您登录后查询");
                    }else{
                        bundle.putString("message", message);
                    }
                    msg.setData(bundle);
                    msg.what = 2;
                    handler.sendMessage(msg);
                }
            } else {
                // 响应失败
                // 在这里处理失败情况
                msg.what = 3;
                handler.sendMessage(msg);
            }
            // 记得关闭响应体
            response.close();
        } catch (IOException e) {
            if (e.toString().contains("request failed")) {
                msg.what = 4;
                handler.sendMessage(msg);
            } else {
                msg.what = 5;
                handler.sendMessage(msg);
            }
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
            msg.what = 3;
            handler.sendMessage(msg);
        }
    }

步骤三:处理返回信息,在主线程中进行UI展示

java 复制代码
// 在主线程中创建 Handler
    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //根据信息编码及数据做出相对应的处理
            switch (msg.what) {
                case 1:
                {
                    Bundle bundle = msg.getData();
                    servicePersonShortBeanList = (ArrayList<ServicePersonShortBean>) bundle.getSerializable("servicePersonShortBeanList");
                    showServicerList();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            loadMoreData();
                        }
                    }).start();
                    break;
                }
                case 2:
                {
                    Bundle bundle = msg.getData();
                    String message = bundle.getString("message");
                    Toast.makeText(ServicePersonListActivity.this, message,Toast.LENGTH_SHORT).show();
                    break;
                }
                case 3:
                    Toast.makeText(ServicePersonListActivity.this, "获取xxx信息失败,请稍后再试!", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    Toast.makeText(ServicePersonListActivity.this, "网络请求失败,请稍后重试", Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    Toast.makeText(ServicePersonListActivity.this, "网络异常,请检查您的网络\"", Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                {
                	//加载更多
                    Bundle bundle = msg.getData();
                    ArrayList<ServicePersonShortBean> moreServicePersonShortBeanList = (ArrayList<ServicePersonShortBean>) bundle.getSerializable("moreServicePersonShortBeanList");
                    servicePersonShortBeanList.addAll(moreServicePersonShortBeanList);
                    servicePersonAdapter.notifyDataSetChanged();
                    break;
                }
                default:
                    break;
            }
        }
    };

注:链式调用写法举例

java 复制代码
FormBody formBody = formBody = new FormBody.Builder()
                                            .add("token", token)
                                            .add("id", id)
                                            .build();
相关推荐
Digitally2 小时前
如何用5种实用方法将电脑上的音乐传输到安卓手机
android·智能手机·电脑
HahaGiver6663 小时前
Unity与Android原生交互开发入门篇 - 打开Unity游戏的设置
android·unity·交互
2501_915909064 小时前
WebView 调试工具全解析,解决“看不见的移动端问题”
android·ios·小程序·https·uni-app·iphone·webview
IT乐手5 小时前
android 下载管理工具类
android
2501_915106326 小时前
App 怎么上架 iOS?从准备资料到开心上架(Appuploader)免 Mac 上传的完整实战流程指南
android·macos·ios·小程序·uni-app·iphone·webview
科技峰行者7 小时前
安卓16提前发布能否改写移动生态格局
android
蒲公英少年带我飞7 小时前
Android NDK 编译 protobuf
android
沐怡旸7 小时前
【底层机制】ART虚拟机深度解析:Android运行时的架构革命
android·面试
小禾青青8 小时前
uniapp安卓打包遇到报错:Uncaught SyntaxError: Invalid regular expression: /[\p{L}\p{N}]/
android·uni-app
studyForMokey8 小时前
【Kotlin内联函数】
android·开发语言·kotlin