java 通过json中的rest api发送pdf数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37753083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending pdf data through rest api inside json
提问by rasty
I have made a webservice that send multiple pdfs as response to client using mutlipart/formdata but as it happens one of the client is salesforce which does not support mutlipart/ formdata.
我制作了一个网络服务,它使用 mutlipart/formdata 向客户端发送多个 pdf 作为响应,但碰巧其中一个客户端是不支持 mutlipart/formdata 的 salesforce。
They want a json in response like - { "filename": xyzname, "fileContent": fileContent }
他们想要一个 json 响应,如 - { "filename": xyzname, "fileContent": fileContent }
I tried encoding data in Base64 using apache codec library but pdf on client side seems to get corrupted and I am unable to open it using acrobat.
我尝试使用 apache 编解码器库在 Base64 中编码数据,但客户端的 pdf 似乎已损坏,我无法使用 acrobat 打开它。
Please find code below -
请在下面找到代码 -
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());
}
-------------------------------
Kindly advise.
好心提醒。
回答by The_GM
I would change from using "Safe" to just using "string". So change: encodeBase64URLSafeString(...) to: encodeBase64String(...)
我将从使用“安全”更改为仅使用“字符串”。所以将:encodeBase64URLSafeString(...) 改为:encodeBase64String(...)
The reason is that the "safe" versions actually change the content to preserve URLs before encrypting - I'm totally uncertain what that would do to a PDF, but suspect it is the source of your problem.
原因是“安全”版本实际上在加密之前更改了内容以保留 URL - 我完全不确定这会对 PDF 产生什么影响,但怀疑它是您问题的根源。
If that doesn't do it for you, I suggest encrypting/decrypting right on the server (or a separate test app) and comparing the results while you try to work it out. That way you can see if what you are doing is working, but don't have to go through the whole "start the server, start the client, connect..." process each time, and it will speed your debugging.
如果这对您不起作用,我建议您直接在服务器(或单独的测试应用程序)上加密/解密,并在您尝试解决时比较结果。这样你就可以看到你正在做的事情是否有效,但不必每次都经历整个“启动服务器,启动客户端,连接......”过程,它会加速你的调试。
回答by rasty
Yes so the problem was with the client.
是的,所以问题出在客户端。
while decoding we should use
在解码时我们应该使用
byte[] decodedBytes = Base64.decodeBase64(fileJson.getString("fileContent"));
rather than
而不是
byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());
Since encoded data.toString() yields some think else
由于编码的 data.toString() 产生了一些其他想法
Also replaced encodeBase64URLSafeString with encodeBase64String Well quite a simple solution :)
还用 encodeBase64String 替换了 encodeBase64URLSafeString 嗯,这是一个非常简单的解决方案:)
回答by FXLima
In my REST application with PHP:
在我使用 PHP 的 REST 应用程序中:
? 1. Send the data encoded in base64 $data = base64_encode($data)
to REST.
? 1.将base64编码的数据发送$data = base64_encode($data)
到REST。
? 2. Before writing the file, I decode $data = base64_decode($data)
.
? 2.在写文件之前,我解码$data = base64_decode($data)
.
? 3. Therefore, when the file is downloaded, it is already in the correct format.
? 3. 因此,当文件被下载时,它已经是正确的格式。
回答by seBaka28
We are doing the same, basically sending PDF as JSON to Android/iOS and Web-Client (so Java and Swift).
我们也在做同样的事情,基本上将 PDF 作为 JSON 发送到 Android/iOS 和 Web 客户端(Java 和 Swift)。
The JSON Object:
JSON 对象:
public class Attachment implements Serializable {
private String name;
private String content;
private Type contentType; // enum: PDF, RTF, CSV, ...
// Getters and Setters
}
And then from byte[] content it is set the following way:
然后从 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));
}
Client Side Java we create our own file type object first before mapping to java.io.File:
客户端 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;
}
And finally:
最后:
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);
}
}