我正在尝试编写 Java 代码以使用其文档 API 将文章 PDF 上传到 Mendeley,但我一直收到 500 错误。我是 Java 新手,所以我可能只是使用了错误的代码或库。最终,目标是通过其文档 API 将文章 PDF 发送到 Mendeley,以便我可以检索有关该文章的元数据。
作为参考,这里是我试图在 Java 中复制的 Mendeley API 文档中提供的 curl 代码:
curl 'https://api.mendeley.com/documents' \
-X POST \
-H 'Authorization: Bearer ACCESS_TOKEN' \
-H 'Content-Type: application/pdf' \
-H 'Content-Disposition: attachment; filename="example.pdf"' \
--data-binary @example.pdf
我能够使用 Python 和 requests 库让它工作。当我使用错误的访问令牌时,我收到 401 错误,因此我知道 API 正在接收我的查询。返回的 500 错误不包含其他错误文本。
// setup connection
String url = "https://api.mendeley.com/documents";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
// set headers
String ACCESS_TOKEN = getApiValue("api_token");
con.setRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);
con.setRequestProperty("Content-Type", "application/pdf");
con.setRequestProperty("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// send PDF
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
File pdfFile = new File(fileName);
byte[] buf = new byte[8192];
InputStream pdfIS = new FileInputStream(pdfFile);
int c = 0;
while ((c = pdfIS.read(buf, 0, buf.length)) > 0) {
wr.write(buf, 0, c);
wr.flush();
}
wr.close();
pdfIS.close();
// get results
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();