Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multipart response, sent from resteasy to android, using okHttp?

I want to upload list of files (images in my case) from JBoss server to android. I am doing so by the below written code:

@GET
@Path("/report/{filename}")
@Produces({MediaType.MULTIPART_FORM_DATA})
public MultipartFormDataOutput getReport(@PathParam("filename") String filename, @Context HttpServletRequest request) {
    try {
        String token = request.getHeader("Authorization");
        List<File> file = processImage.getImage(filename,token);
        MultipartFormDataOutput output = new MultipartFormDataOutput();
        for(File image: file){
        System.out.println("class of this" +image + "MMMM" +image.exists());
        output.addPart(image, new MediaType("image","jpg"));
        }
        return output;

    } .....
      .......
}

On Android side I want to read the response (the files in multipart form). I am using okHttp to make the connection. Searching a lot on internet I tried the below code to read the multipart response, but it is not working. It seems that is not reading anything from the stream.

ByteArrayDataSource ds = new ByteArrayDataSource(response.body().byteStream(), "multipart/form-data");
            MimeMultipart multipart = new MimeMultipart(ds);
            BodyPart jsonPart = multipart.getBodyPart(0);

            System.out.println("Response body = " + jsonPart.getInputStream());
            File reportFile = new File(Environment.getExternalStorageDirectory() + File.separator + "downloadedFile.jpg");
            InputStream is = jsonPart.getInputStream();
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(reportFile);
                byte[] buffer = new byte[MEGABYTE];
                int bufferLength = 0;

                while ((bufferLength = is.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, bufferLength);
                }
                is.close();
                fileOutputStream.close();   
                  .......
            }

Can anyone please help me solving this. I am stuck here from 2 days. What am I doing wrong .

like image 860
Yoda Avatar asked Sep 03 '25 09:09

Yoda


1 Answers

You can do the following:

  • Create an async task to run in the background
  • Use okhttp3.Request to create the request
  • Create OkHttpClient to send the request and save the response in okHttp3 Response
  • Then get the response body from the okhttp3.ResponseBody and use InputStreamReader and BufferedReader to read the files.

Something like following should work:

private class FileTask extends AsyncTask<Void, Void, Void> {
   private File file = null;
    @Override
    protected Void doInBackground(Void... params) {

        okhttp3.Request request = new okhttp3.Request.Builder()
                .url("Your URL for getReport()")
                .get()
                .build();
        OkHttpClient okHttpClient = new OkHttpClient.Builder().
                        connectTimeout(80, TimeUnit.SECONDS)
                        .writeTimeout(80, TimeUnit.SECONDS)
                        .readTimeout(80, TimeUnit.SECONDS)
                        .build();


        try {
            Response response = okHttpClient.newCall(request).execute();
            okhttp3.ResponseBody in = response.body();
            InputStream is = in.byteStream();
            InputStreamReader inputStreamReader = new InputStreamReader(is);
            BufferedReader buffReader = new BufferedReader(inputStreamReader);

            file = new File(Environment.getExternalStorageDirectory() + File.separator + "filename.txt"); //Your output file
            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(output);


            String line=buffReader.readLine();
            while ((line=buffReader.readLine()) != null) {
                output.write(line.getBytes());
                output.write('\n');
            }
            buffReader.close();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //do post execution steps
        }
    }
}
like image 125
edeesan Avatar answered Sep 05 '25 00:09

edeesan