Share via

File upload to Share Point online using Java

Anonymous
2018-04-27T06:45:21+00:00

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

Microsoft 365 and Office | SharePoint | For business | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Anonymous
    2018-04-27T11:18:26+00:00

    Hi Gautam,

    Since the problem is related to the code in SharePoint Online, we suggest you post a thread in our MSDN forum for the expert assistance.

    Thanks for your understanding.

    Tisky

    0 comments No comments