3

我正在创建一个 java 进程来使用他们的 NBR API 的 NBRFileOpenService 调用下载 WebEx 录音。它返回带有附加记录文件内容的多部分响应。我有一些使用下面的代码。但是,当录制文件足够大时,我会遇到OutOfMemoryError异常。

录音很大是很常见的,如果 API 只返回文件单独,我可以只流式下载,但是我不太确定如何安全地处理多部分响应。所以我想知道是否有任何方法可以读取文件元数据并将二进制内容保存到文件中,而不会将整个响应保存在内存中。

API 响应格式:

------=_Part_674_458057647.1593732813745
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: binary
Content-Id: <AD79B5747EFC01CDDA9A281BA8CDEF0C>

[SOAP RESPONSE]
------=_Part_674_458057647.1593732813745
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-Id: <C498AB4664B57130F869695A1C5B584E>

[FILE METADATA]
------=_Part_674_458057647.1593732813745
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-Id: <003D9EBA1E491CE2E9E5903C996EFD4C>

[BINARY FILE CONTENT]
------=_Part_674_458057647.1593732813745--

我的代码:

public void retrieveRecordingFile(String uri, String recordId, String serviceType) throws Exception {
    HttpClient httpClient = generateHttpClient();
    
    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", ContentType.APPLICATION_XML.getMimeType());
    httpPost.addHeader("SOAPAction", "NBRFileOpenService");
    
    String requestXml = buildNBRDownloadFileXml(recordId, serviceType);
    HttpEntity httpEntity = new ByteArrayEntity(requestXml.getBytes(Charset.forName("UTF-8")));
    
    httpPost.setEntity(httpEntity);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        MimeMultipart mimeMultipart = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(), "multipart/form-data"));
        String filename = null;
        File targetFile = null;
        for (int i = 0; i < mimeMultipart.getCount(); i++) {
            if (i == 1) {
                filename = retrieveFileName(mimeMultipart.getBodyPart(i).getInputStream());
            } else if (i == 2) {
                targetFile = new File(DOWNLOAD_DIR + filename);
                FileUtils.copyInputStreamToFile(mimeMultipart.getBodyPart(i).getInputStream(), targetFile);
            }
        }
    }
}

任何帮助都非常感谢。

4

0 回答 0