[SalesForce] Download and save contentVersion file JAVA

Please help me with download contentversion of PDF and save to file in java.

I have a problem with base64. RestAPI return content in base64 but when I save it to file I have a blank page when I opened it in adobe reader. When I compare content with original file I see a difference. Please, what do I have to do differently?

String fileContent = 
    SFApi.getFileContentBySalesForceId("0689E00000022MKADCW");
    System.out.println(fileContent);
    assertNotNull(fileContent);
    Date date = new Date();
    String attachName = "pdf_" + date.getTime() + ".pdf";
    File outputFile = new File("c:/test/tmp/"+attachName);
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile));
        bos.write(fileContent.getBytes());
        bos.flush();
        bos.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I get content file by

run GET url :

/services/data/v40.0/sobjects/ContentVersion/0689E00000022MKADCW/VersionData

EDIT:

When I get content by widget on linux and save to file I can open file properly.

When I get content in JAVA using:

protected String getFileContentBySalesForceId(String fileSalesForceId) {
    Assert.notNull(fileSalesForceId, "Sales Force file id cannot be null.");
    HttpGet httpGet = new HttpGet(clientURL + "/services/data/v40.0/sobjects/ContentVersion/" + fileSalesForceId + "/VersionData");
    String accesToken = refreshToken();
    httpGet.addHeader("Authorization", "Bearer " + accesToken);
    HttpResponse response = null;
    String getResult = null;
    try {
        response = httpclient.execute(httpGet);
        getResult = EntityUtils.toString(response.getEntity());
        EntityUtils.consume(response.getEntity());
    } catch (ParseException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        log.error("Error authenticating to Force.com: " + statusCode);
        return null;
    }

    return getResult;
}

And save to file by the first method in post, I get a blank page in PDF.

Maybe I need different settings in header?

EDIT:

Need set charset

 bos.write(fileContent.getBytes("ISO-8859-1"));

Best Answer

You need to base64 decoded the data before writing into file.

Since most of the times, attachments are binary data, Salesforce encodes as base64 string. You need to convert that to binary bytes by decoding the base64 string.