【发布时间】:2019-12-23 16:17:33
【问题描述】:
我必须构建一个像这样的 JSON 对象:
{
"sessionId": "DA2F5102377742BE8063ADBC8968A294",
"documentId": "c2f84034-ea1c-4406-8a8b-ab2c00a1b537",
"sourceFile": {
"MimeType": "application/pdf",
"SourceFile": [
25,
68,
56,...
]
}
为此,我创建了 2 个 POJO:
@Component
@Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public class UpdateSourceFileRequestModel {
private String sessionId;
private ReportingDataRequestModel reportingData;
private String documentId;
private DocumentSourceFileRequestModel sourceFile;
}
还有:
@Component
@Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public class DocumentSourceFileRequestModel {
// for GettingSourceFile
@SerializedName("MimeType")
private String mimeType;
@SerializedName("SourceFile")
private int[] sourceFile;
}
我必须使用 SerializedName,因为 JSON 区分大小写。到目前为止一切顺利,直到那里一切都很好。
现在,我正在尝试将 pdf 文件转换为字节数组。通过阅读文件可以轻松完成:
byte[] array = Files.readAllBytes(Paths.get(fileToReturn));
我的问题是我必须返回一个 C# 字节数组(从 0 到 255 的无符号数)。 为了解决这个问题,我尝试了这个:
int[] result = new int[array.length];
for(int i = 0; i < array.length; i++) {
int posInt = array[i] & 0xFF;
byte bValue = (byte) posInt;
result[i] = bValue;
}
我复制了一个有符号字节数组(-128 +127)并将其转换为一个整数数组(0 到 255),以符合 API 的要求。这段代码是在 stackoverflow 上找到的。我的问题是 acrobat 无法读取转换后的文件。
这是整个方法代码:
private void updateSourceFile(String fileToReturn, LogOnWithPassword2RestResponseModel login) throws IOException {
System.out.println("\nSending HTTP POST request - returning file process");
// retrieve the file
Path path = Paths.get(fileToReturn);
File f = path.toFile();
// convert file to byte array
byte[] array = Files.readAllBytes(Paths.get(fileToReturn));
int[] result = new int[array.length];
for(int i = 0; i < array.length; i++) {
int posInt = array[i] & 0xFF;
byte anotherB = (byte) posInt;
result[i] =anotherB;
}
UpdateSourceFileRequestModel updateSourceFileRequestModel = new UpdateSourceFileRequestModel();
DocumentSourceFileRequestModel documentSourceFileRequestModel = new DocumentSourceFileRequestModel();
documentSourceFileRequestModel.setMimeType("application/pdf");
documentSourceFileRequestModel.setSourceFile(result);
updateSourceFileRequestModel.setSessionId(login.getD().getSessionId());
updateSourceFileRequestModel.setDocumentId(docId);
updateSourceFileRequestModel.setSourceFile(documentSourceFileRequestModel);
updateSourceFileRequestModel.setReportingData(null);
String url = "http://localhost/TotalAgility/Services/SDK/CaptureDocumentService.svc/json/UpdateSourceFile";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String jsonInputString = gson.toJson(updateSourceFileRequestModel);
StringEntity postingString = new StringEntity(jsonInputString);
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
post.setHeader("accept", "application/json");
HttpResponse response = httpClient.execute(post);
}
【问题讨论】: