无法解码Base64编码对象

时间:2013-09-29 21:36:39

标签: java object salesforce base64 decode

我使用salesforce api在本地计算机上获取salesforce文档。该文档是base64编码的。它作为Object类型返回。当我尝试解码它以将其保存在我的本地机器上时,它会出现'java.lang.ArrayIndexOutOfBoundsException:-84'错误。我知道当我们尝试访问数组中不存在的索引时会发生这种情况,但我在这里没有这样做。我正在使用公共图书馆。

你们中的任何人都可以帮助我或建议一种更好的方法来解码和存储我本地机器上的文件。

import org.apache.commons.codec.binary.Base64; //and other imports
private void querySample() {
    try {
        // Set query batch size
        partnerConnection.setQueryOptions(250);

        // SOQL query to use
        String soqlQuery = "SELECT Name, Body, BodyLength FROM Document LIMIT 1";
        // Make the query call and get the query results
        QueryResult qr = partnerConnection.query(soqlQuery);

        boolean done = false;
        SObject document;
        Object docName;
        Object docBody;
        Object bodyLength;
        byte[] encoded;
        byte[] decoded;
        int loopCount = 0;
        // Loop through the batches of returned results
        while (!done) {
            System.out.println("Records in results set " + loopCount++
                    + " - ");
            SObject[] records = qr.getRecords();
            // Process the query results
            for (int i = 0; i < records.length; i++) {
                document = records[i];
                docName = document.getField("Name");
                docBody = document.getField("Body");            //Body is base 64
                bodyLength = document.getField("BodyLength");

                encoded = serialize(docBody);
                Integer size = Integer.parseInt((String) bodyLength);

                decoded = new byte[size];   

                decoded = Base64.decodeBase64(encoded); //<-- Getting error here

                String path = "D:\\myImage.png";
                OutputStream out1 = new BufferedOutputStream(
                        new FileOutputStream(path));
                out1.write(decoded);

            }
            if (qr.isDone()) {
                done = true;
            } else {
                qr =   partnerConnection.queryMore(qr.getQueryLocator());
            }

        }
    } catch (ConnectionException ce) {
        ce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    System.out.println("\nQuery execution completed.");

}

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    ObjectOutputStream o = new ObjectOutputStream(b);
    o.writeObject(obj);
    return b.toByteArray();
}

0 个答案:

没有答案