Share via


File upload to Share Point online using Java

Question

Friday, April 27, 2018 6:47 AM

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

All replies (3)

Monday, April 30, 2018 8:02 AM

About your code, it seems that it caused by the URL and the token.

Besides, I suggest you use the C# to upload file to the SharePoint document library.

You can refer to the following code.

using Microsoft.SharePoint.Client;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Threading.Tasks;

namespace UploadSPOnlineDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                const string USERNAME = "<User Name>";
                const string PWD = "Password";
                const string WEB = "<Site URL>";
                const string DOCNAME = @"<file address>";
                const string FOLDERURL = "<Folder URL>";

                //Reading document from file system
                System.IO.MemoryStream doc = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(DOCNAME));

                //Uploading document
                var t = uploadDocumentAsync(WEB, USERNAME, PWD, doc, FOLDERURL, System.IO.Path.GetFileName(DOCNAME));
                t.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadLine();
        }

        /// <summary>
        /// Return Form Digest information
        /// </summary>
        /// <param name="handler"></param>
        /// <param name="webUrl"></param>
        /// <returns></returns>
        private static async Task<Models.FormDigestInfo.Rootobject> GetFormDigest(HttpClientHandler handler, string webUrl)
        {
            //Creating REST url to get Form Digest
            const string RESTURL = "{0}/_api/contextinfo";
            string restUrl = string.Format(RESTURL, webUrl);

            //Adding headers
            var client = new HttpClient(handler);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata");

            //Perform call
            HttpResponseMessage response = await client.PostAsync(restUrl, null).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            //Reading string data
            string jsonData = await response.Content.ReadAsStringAsync();

            //Creating FormDigest object
            Models.FormDigestInfo.Rootobject res = JsonConvert.DeserializeObject<Models.FormDigestInfo.Rootobject>(jsonData);
            return res;
        }

        /// <summary>
        /// Upload a document
        /// </summary>
        /// <param name="webUrl"></param>
        /// <param name="loginName"></param>
        /// <param name="pwd"></param>
        /// <param name="document"></param>
        /// <param name="folderServerRelativeUrl"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static async Task uploadDocumentAsync(string webUrl, string loginName, string pwd, System.IO.MemoryStream document, string folderServerRelativeUrl, string fileName)
        {
            try
            {
                //Creating credentials
                var passWord = new SecureString();
                foreach (var c in pwd) passWord.AppendChar(c);
                SharePointOnlineCredentials credential = new SharePointOnlineCredentials(loginName, passWord);

                //Creating REST url
                const string RESTURL = "{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/Files/add(url='{2}',overwrite=true)";
                string rESTUrl = string.Format(RESTURL, webUrl, folderServerRelativeUrl, fileName);

                //Creating handler
                using (var handler = new HttpClientHandler() { Credentials = credential })
                {
                    //Getting authentication cookies
                    Uri uri = new Uri(webUrl);
                    handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

                    //Getting form digest
                    var tFormDigest = GetFormDigest(handler, webUrl);
                    tFormDigest.Wait();

                    //Creating HTTP Client
                    using (var client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.Add("Accept", "application/json;odata=nometadata");
                        client.DefaultRequestHeaders.Add("binaryStringRequestBody", "true");
                        client.DefaultRequestHeaders.Add("X-RequestDigest", tFormDigest.Result.FormDigestValue);
                        client.MaxResponseContentBufferSize = 2147483647;

                        //Creating Content
                        ByteArrayContent content = new ByteArrayContent(document.ToArray());

                        //Perform post
                        HttpResponseMessage response = await client.PostAsync(rESTUrl, content).ConfigureAwait(false);

                        //Ensure 200 (Ok)
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Error uploading document {fileName} call on folder {folderServerRelativeUrl}. {ex.Message}", ex);
            }
        }
    }

    public class Models
    {
        public class FormDigestInfo
        {
            public class Rootobject
            {
                public int FormDigestTimeoutSeconds { get; set; }
                public string FormDigestValue { get; set; }
                public string LibraryVersion { get; set; }
                public string SiteFullUrl { get; set; }
                public string[] SupportedSchemaVersions { get; set; }
                public string WebFullUrl { get; set; }
            }
        }
    }
}

This is a reference about how to upload files from FileSystem to SharePoint online using CSOM.

https://blogs.msdn.microsoft.com/bhumi/2016/07/13/upload-files-from-filesystem-to-sharepoint-online-using-csom/

Best Regards,

Carl Zhou

Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact [email protected].


Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.


Monday, April 30, 2018 10:31 AM

Hi Carl,

Thanks for your suggestion but my project is already in place using java for transformations of excel files and after transformation we need to archive it to SP. So here C# is not an option for me.

Could you please help me with the code I have sent. Is there anything I am missing.

Thanks & Regards,

Gautam


Tuesday, July 30, 2019 8:15 PM

Hi Gautam,

Did you get a solution for this?

Regards

Kishan