I am getting the below error while trying to upload file to Share point Online using Java using clientid and client secret :
java.io.IOException: Server returned HTTP response code: 403
I have followed the steps mentioned in the below url to get the access token and the digest.
https://wpoffice365.com/access-sharepoint-online-using-postman/
Below is my code to uplaod the file.
String fileName = "File.xlsx";
FileInputStream inputStream = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(inputStream);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
workbook.write(bos);
} finally {
bos.close();
}
byte[] bytes = bos.toByteArray();
workbook.close();
String url =https://XXXX.sharepoint.com/sites/Test/_api/Web/GetFolderByServerRelativeUrl('/sites/Test/Documents')/Files/add(url='FileName',overwrite=true);
URL obj = new URL(url);
System.out.println("getting Connection");
HttpURLConnection conn2 = (HttpURLConnection) obj.openConnection();
conn2.setRequestMethod("POST");
conn2.addRequestProperty("User-Agent", "Mozilla/4.76");
System.out.println("setting Connection property");
// add request header
conn2.setRequestProperty("Accept", "application/json; odata=verbose");
conn2.setRequestProperty("X-RequestDigest", formDigestValue);
conn2.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn2.setRequestProperty("Content-Length", String.valueOf(bytes.length));
conn2.setRequestProperty("Authorization","Bearer Access_Token");
conn2.setDoInput(true);
conn2.setDoOutput(true);
System.out.println("setting out stream");
// Write data
OutputStream os = conn2.getOutputStream();
// InputStream ir=conn2.getInputStream();
os.write(bytes);
StringBuilder responseSB = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn2.getInputStream()));
String line;
while ((line = br.readLine()) != null)
responseSB.append(line);
// Close streams
br.close();
os.close();
if (conn2.getResponseCode() == 200)
System.out.println("File uploaded successfully");
else
System.out.println("File upload failed " + conn2.getResponseCode());
conn2.disconnect();
Please assist.
Thanks & Regards,
Guatam