通过json中的rest api发送pdf数据

ras*_*sty 6 java pdf rest base64 salesforce

我制作了一个网络服务,它使用 mutlipart/formdata 向客户端发送多个 pdf 作为响应,但碰巧其中一个客户端是不支持 mutlipart/formdata 的 salesforce。

他们想要一个 json 响应,如 - { "filename": xyzname, "fileContent": fileContent }

我尝试使用 apache 编解码器库在 Base64 中编码数据,但客户端的 pdf 似乎已损坏,我无法使用 acrobat 打开它。

请在下面找到代码 -

import org.apache.commons.io.FileUtils;
//------Server side ----------------
@POST
@Consumes(MULTIPART_FORM_DATA)  
@Produces(MediaType.APPLICATION_JSON)
@Path("somepath")
public Response someMethod(someparam)   throws Exception
{
....
JSONArray filesJson = new JSONArray();
String base64EncodedData =      Base64.encodeBase64URLSafeString(loadFileAsBytesArray(tempfile));
JSONObject fileJSON = new JSONObject();
fileJSON.put("fileName",somename);
fileJSON.put("fileContent", base64EncodedData);
filesJson.put(fileJSON);
.. so on ppopulate jsonArray...
//sending reponse
responseBuilder =    Response.ok().entity(filesJson.toString()).type(MediaType.APPLICATION_JSON_TYPE)    ;
response = responseBuilder.build();   
}

//------------Client side--------------

Response clientResponse = webTarget.request()
            .post(Entity.entity(entity,MediaType.MULTIPART_FORM_DATA));
String response = clientResponse.readEntity((String.class));
JSONArray fileList = new JSONArray(response);
for(int count= 0 ;count< fileList.length();count++)
{
JSONObject fileJson = fileList.getJSONObject(count);        
byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());
outputFile = new File("somelocation/" + fileJson.get("fileName").toString()   + ".pdf");                    
FileUtils.writeByteArraysToFile(outputFile,        fileJson.get("fileContent").toString().getBytes());
}

-------------------------------
Run Code Online (Sandbox Code Playgroud)

好心提醒。

小智 0

我将从使用“安全”更改为仅使用“字符串”。因此,将:encodeBase64URLSafeString(...)更改为:encodeBase64String(...)

原因是“安全”版本实际上会在加密之前更改内容以保留 URL - 我完全不确定这会对 PDF 产生什么影响,但怀疑这是问题的根源。

如果这不适合您,我建议在服务器(或单独的测试应用程序)上进行加密/解密,并在您尝试解决问题时比较结果。这样你就可以看到你正在做的事情是否有效,但不必每次都经历整个“启动服务器,启动客户端,连接......”过程,并且它将加快你的调试速度。