4

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 .

Yoda
  • 323
  • 6
  • 14

3 Answers3

1

Are you possibly using HttpLoggingInterceptor with setLevel(HttpLoggingInterceptor.Level.BODY)? I used your code to successfully parse a multipart response. But once I change the level from HEADERS to BODY, that code no longer works, and acts as if it is not reading anything from the stream. I already reported the issue: https://github.com/square/okhttp/issues/3269

By the way, thanks for giving me sample code to allow me to parse a multipart body with OkHttp. For others who may come along, I had to add this to my maven pom.xml:

    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.5.6</version>
    </dependency>
Sam Mefford
  • 2,465
  • 10
  • 15
1

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
        }
    }
}
edeesan
  • 326
  • 3
  • 16
0

try this:

 //first you should convert image into bytearray


 VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {

            System.out.println(" response"+response.data);


            String resultResponse = new String(response.data);
            System.out.println("-------------  response-----------------"+resultResponse);

            try {
                JSONObject jsonObject = new JSONObject(resultResponse);
                sStatus = jsonObject.getString("status");


                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            dialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            dialog.dismiss();

            NetworkResponse networkResponse = error.networkResponse;
            String errorMessage = "Unknown error";
            if (networkResponse == null) {
                if (error.getClass().equals(TimeoutError.class)) {
                    errorMessage = "Request timeout";
                } else if (error.getClass().equals(NoConnectionError.class)) {
                    errorMessage = "Failed to connect server";
                }
            } else {
                String result = new String(networkResponse.data);
                try {
                    JSONObject response = new JSONObject(result);
                    String status = response.getString("status");
                    String message = response.getString("message");

                    Log.e("Error Status", status);
                    Log.e("Error Message", message);

                    if (networkResponse.statusCode == 404) {
                        errorMessage = "Resource not found";
                    } else if (networkResponse.statusCode == 401) {
                        errorMessage = message + " Please login again";
                    } else if (networkResponse.statusCode == 400) {
                        errorMessage = message + " Check your inputs";
                    } else if (networkResponse.statusCode == 500) {
                        errorMessage = message + " Something is getting wrong";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Log.i("Error", errorMessage);
            error.printStackTrace();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("id",ID);
            System.out.println("id---------------"+ID);
            return params;
        }

        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            params.put("image",new DataPart("imnage.jpg", byteArray));

            return params;
        }
    }

    AppController.getInstance().addToRequestQueue(multipartRequest);

}
MurugananthamS
  • 2,395
  • 4
  • 20
  • 49
  • Your response uses VolleyMultipartRequest which appears to depend on apache httpclient. The question was how to do this using okhttp, not httpclient. – Sam Mefford Apr 06 '17 at 19:34