'file upload sharepoint online giving 403 forbidden error

I am trying this below rest api code to upload a text file to share point. But response is 403 forbidden.

I have all the required permissions, directly I am able to create file in the share point site.

Also rest api file download is working fine. But upload api is failing.

Can anyone please guide where am I missing here?

HttpPost postRequest = new HttpPost(url);
        postRequest.addHeader("Cookie", token.getLeft() + ";" + token.getRight());
        postRequest.addHeader("accept", "application/json;odata=verbose");
        postRequest.addHeader("content-type", "application/json;odata=verbose");
        postRequest.addHeader("X-RequestDigest", formDigestValue);
        PostRequest.setEntity(new FileEntity(file));
        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 204) {
            System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + ", ");
        }


Solution 1:[1]

Found the solution. It's the digest header change that worked.

Before:

connection.addRequestProperty("X-RequestDigest", formDigestValue);

After:

connection.addRequestProperty("Authorization", "Bearer "+formDigestValue);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RiveN