写在了线程池里边。

public static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(8);
//登录按钮的点击事件
case R.id.btn_devOps_login:
                if (null == et_userName.getText() || "".contentEquals(et_userName.getText())){
                    ToastUtil.showTextToast(context,"账号不能为空");
                }else if (null == et_passWord.getText() || "".contentEquals(et_passWord.getText())){
                    ToastUtil.showTextToast(context,"密码不能为空");
                }else{
                    CommonContext.fixedThreadPool.submit(new sendRequestWithOkHttp());
                }
                break;

Http请求:

 private class sendRequestWithOkHttp implements Runnable{

        @Override
        public void run() {
            JSONObject object = new JSONObject();
            try {
                object.put("username",et_userName.getText().toString());
                object.put("password",et_passWord.getText().toString());
            }catch (JSONException e){
                e.printStackTrace();
            }
            MediaType type = MediaType.parse("application/json;charset = utf-8");
            RequestBody requestBody = RequestBody.create(type,"" + object.toString());
            try {
                OkHttpClient client = new OkHttpClient();
                StringBuilder sb = new StringBuilder(baseUrl + "/auth/login");

                Request request = new Request.Builder()
                        .url(sb.toString())
                        .post(requestBody)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
//                            ToastUtil.showTextToast(requireActivity(),"服务网络错误");
                        Looper.prepare();
                        ToastUtil.showTextToast(context,"服务网络错误");
//                            Toast.makeText(context, "服务网络错误", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.header("token");
                        showResponse(responseData);
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐