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 = 
    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));
    } catch (Exception e) {
        // TODO Auto-generated catch block

I get content file by

run GET url :



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());
    } catch (ParseException | IOException e) {
        // TODO Auto-generated catch block

    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?


Need set charset

  • You can't safely convert the binary response from the rest api endpoint into a Java string, you need to treat it either as a Stream or as a byte array.
    – superfell
    Sep 29, 2017 at 16:08

1 Answer 1


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.

  • 1
    requests to the rest endpoint for the blob field, should return straight up binary data, not base64 encoded.
    – superfell
    Sep 29, 2017 at 16:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .