In Android Does multipart entity is used for download file too as I can't see any example or details description for that class

471 views Asked by At

I was asked to look for downloading file using MultiPartEntity in android However i searched a lot but couldn't find any solution where I can download file using MultiPartEntity. it seems it is used to upload files only.

I couldn't find detail description whether it does use for download or not. so helplessly I had to ask the question on stackoverflow. If it does can anyone share a link or code snippet for the same. If it doesn't Please tell this information too. I'll be really glad. Thank you very much in advance.

1

There are 1 answers

0
Rishi On

You can download contents of a file from URL as follows,

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(/*Download URL*/);
/* If you want custom timeout time use this
int TIMEOUT_MILLIS = 1000;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_MILLIS).setConnectTimeout(TIMEOUT_MILLIS).setConnectionRequestTimeout(TIMEOUT_MILLIS).build();
*/
RequestConfig requestConfig = RequestConfig.DEFAULT;
httpPost.setConfig(requestConfig);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
String responseLine = null;
if (response != null && response.getStatusLine().getStatusCode() == 200) {
    BufferedReader bufferedReader = null;
    InputStreamReader streamReader = null;
    String line = null;
    try {
        streamReader = new InputStreamReader(response.getEntity().getContent());
        bufferedReader = new BufferedReader(streamReader);
        StringBuilder responseBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            responseBuilder.append(line);
        }
        responseLine = responseBuilder.toString();
    } catch (Exception exception) {
        //Handle Exceptions
    } finally {
        bufferedReader.close();
        streamReader.close();
    }
}