Search code examples
javaandroidandroid-asynctaskokhttprest

How should I put code in Background Thread in Java?


I am using an API which uploads some data to the server, I am deploying this on android application.

I tested APIs using Postman and it works absolutely fine and generated code from postman

login code:

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("username","[email protected]")
  .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();

create user and upload photo

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();

Now I want to know that how can I put these code in AsyncTask class and make the necessary code in background.


Solution

  • You can call enqueue method instead of execute and it will work on the background thread:

    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
        }
    });