我已經做了一個web服務,發送多個pdf作爲響應客戶端使用mutlipart/formdata,但事實上,其中一個客戶端是salesforce,它不支持mutlipart/formdata。發送pdf數據通過休息api裏面json
他們希望有一個JSON像響應 - { 「文件名」:xyzname, 「fileContent」:fileContent }
我使用Apache的編解碼器庫,但在客戶端PDF似乎得到試圖Base64編碼數據損壞,我無法使用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());
}
-------------------------------
請告知。
感謝resposne。 1.我嘗試了encodeBase64String,它沒有工作。 2.我會在eclipse中構建一些本地代碼來測試,而不是客戶端/ api – rasty
因此,我嘗試了在本地進行編碼和解碼工作,因此問題可能是rest api傳輸數據的方式。 ----------------------------- File inputFile = new File(「some pdf」); 字符串base64EncodedData = Base64。encodeBase64String(loadFileAsBytesArray(partiaFile)); //解碼數據 文件decodeFile = new File(「some other pdf」); byte [] decodedBytes = Base64.decodeBase64(base64EncodedData); writeByteArraysToFile(decodedFile,decodedBytes); – rasty
當然 - 或客戶。 如果您可以使用Postman調用Webservice,請嘗試使用Linux coreutils將結果字符串解碼爲文件,然後嘗試使用PDF查看器打開。這將告訴你它是否是其餘的REST編碼或客戶端處理它的方式。對不起,我不是更直接的幫助,這是一個有趣的問題。 –