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

时间:2016-06-10 16:29:01

标签: java rest pdf base64 salesforce

我已经创建了一个web服务,使用mutlipart / formdata将多个pdf作为响应发送给客户端,但是当它发生时,其中一个客户端是salesforce,它不支持mutlipart / formdata。

他们想要一个响应的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());
}

-------------------------------

请告知。

4 个答案:

答案 0 :(得分:0)

我会从使用“安全”更改为仅使用“字符串”。所以改变: encodeBase64URLSafeString(...) 至: encodeBase64String(...)

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

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

答案 1 :(得分:0)

是的,问题出在客户身上。

解码时我们应该使用

byte[] decodedBytes = Base64.decodeBase64(fileJson.getString("fileContent"));

而不是

byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());

由于编码的data.toString()会产生一些其他的想法

还用encodeBase64String替换了encodeBase64URLSafeString 这是一个非常简单的解决方案:)

答案 2 :(得分:0)

在我的PHP REST应用程序中:

1.将base64 $data = base64_decode($data)中编码的数据发送到REST。

2.在写入文件之前,我解码grep -v '[^,]' file1 > file2

3.因此,下载文件时,文件已经是格式正确

答案 3 :(得分:0)

我们正在做相同的事情,基本上是将PDF作为JSON发送到Android / iOS和Web客户端(因此是Java和Swift)。

JSON对象:

public class Attachment implements Serializable {
    private String name;
    private String content;
    private Type contentType; // enum: PDF, RTF, CSV, ...

    // Getters and Setters
}

然后从byte []内容中进行以下设置:

public Attachment createAttachment(byte[] content, String name, Type contentType) {
    Attachment attachment = new Attachment();
    attachment.setContentType(contentType);
    attachment.setName(name);
    attachment.setContent(new String(Base64.getMimeEncoder().encode(content), StandardCharsets.UTF_8));
}

客户端Java,我们首先创建自己的文件类型对象,然后再映射到java.io.File:

public OurFile getAsFile(String content, String name, Type contentType) {
    OurFile file = new OurFile();
    file.setContentType(contentType);
    file.setName(name);
    file.setContent(Base64.getMimeDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
    return file;
  }

最后:

public class OurFile {
    //...
    public File getFile() {
        if (content == null) {
          return null;
        }
        try {
          File tempDir = Files.createTempDir();
          File tmpFile = new File(tempDir, name + contentType.getFileEnding());
          tempDir.deleteOnExit();
          FileUtils.copyInputStreamToFile(new ByteArrayInputStream(content), tmpFile);
          return tmpFile;
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
     }