I am trying to save file to Sharepoint folder. This is my code:

public void saveFileToFolder(Folder folder, File file) {
    try {

        String token = getSPOIDCRL(folder.getSource());
        HttpClient httpClient = HttpClientBuilder.create().build();

        //calculate folder and file name
        folderName = URLEncoder.encode(folderName, "UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");

        String uri = folder.getSource().getUrl() + "/" + "_api/web/GetFolderByServerRelativeUrl(\'" + folderName + "\')/Files/add(url=\'" + fileName + "\',overwrite=true)";

        byte[] array = Files.readAllBytes(file.toPath());

        HttpPost httppost = new HttpPost(uri);
        httppost.setHeader("Cookie", "SPOIDCRL=" + token);
        httppost.addHeader("Accept", "application/json;odata=verbose");
        httppost.addHeader("Content-Type", "application/json;odata=verbose");

        HttpEntity entity = new ByteArrayEntity(array);

        // Make the request.
        HttpResponse response = httpClient.execute(httppost);
        // Process the result
        int statusCode = response.getStatusLine().getStatusCode();
        //Parse the result if we were able to connect.
        if (statusCode == 200) {
        } else {
    } catch (Exception e) {
        log.error("", e);

This is response I am getting from SP: Status code 403 forbidden.

{"error":{"code":"-2130575251, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The security validation for this page is invalid and might be corrupted. Please use your web browser's Back button to try your operation again."}}}

I just calculated this token (it is not re-used) Same approach works for retrieving list of files in folder, for example.

What I am missing here? Thanks again

1 Answer 1


The following code for your reference:

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)
                const string USERNAME = "[email protected]";
                const string PWD = "xxx";
                const string WEB = "https://xxx.sharepoint.com/sites/xxx";
                const string DOCNAME = @"c:\users\administrator\Desktop\Test.txt";
                const string FOLDERURL = "/sites/xxx/Shared%20Documents/folder";

                //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));
            catch (Exception ex)

        /// <summary>
        /// Return Form Digest information
        /// </summary>
        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.Add("Accept", "application/json;odata=nometadata");

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

            //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>
        private static async Task uploadDocumentAsync(string webUrl, string loginName, string pwd, System.IO.MemoryStream document, string folderServerRelativeUrl, string fileName)
                //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);

                    //Creating HTTP Client
                    using (var client = new HttpClient(handler))
                        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)
            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; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.