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

新手上路,请多包涵

我制作了一个网络服务,使用 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());
}

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

好心提醒。

原文由 rasty 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 651
1 个回答

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

解码时我们应该使用

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

而不是

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

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

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

原文由 rasty 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题