I'm attempting to write Java code to upload an article PDF to Mendeley using its document API, but I keep receiving a 500 error. I'm new to Java, so I might just be using the wrong code or libraries. Ultimately, the goal is to send an article PDF to Mendeley through its document API so that I can retrieve metadata about that article.
For reference, here's curl code provided in the Mendeley API docs that I'm trying to replicate in Java:
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
I was able to get it to work using Python and the requests library. When I use the wrong access token I receive a 401 error, so I know the API is receiving my query. The returned 500 error does not include additional error text.
// 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();