我应该如何将代码放入 Java 中的后台线程?

How should I put code in Background Thread in Java?

我正在使用 API 将一些数据上传到服务器,我正在 android 应用程序上部署它。

我使用 Postman 测试了 APIs,它工作得非常好,并且从 postman

生成了代码

登录码:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("username","abc@abc.com")
  .addFormDataPart("password","E1234567")
  .build();
Request request = new Request.Builder()
  .url("192.168.1.51/auth/login")
  .method("POST", body)
  .addHeader("User-Agent", "Koala Admin")
  .addHeader("Content-Type", "application/json")
  .addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
  .build();
Response response = client.newCall(request).execute();

创建用户并上传照片

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("subject_type","1")
  .addFormDataPart("name","jasim")
  .addFormDataPart("start_time","1619496549")
  .addFormDataPart("end_time","1619525349")
  .addFormDataPart("photo","/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg")))
  .build();
Request request = new Request.Builder()
  .url("192.168.1.51/subject/file")
  .method("POST", body)
  .addHeader("Content-Type", "application/json")
  .addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
  .build();
Response response = client.newCall(request).execute();

现在我想知道如何将这些代码放入 AsyncTask class 并在后台制作必要的代码。

您可以调用 enqueue 方法而不是 execute,它将在后台线程上运行:

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
         // handle your response
    }

    @Override
    public void onFailure(Call call, IOException e) {
         // handle the failure
    }
});