How do I upload a document to SharePoint with Java?

前端 未结 6 1972
余生分开走
余生分开走 2020-12-30 03:47

I\'m creating some big files (DB exports) with Java and I need to put them somewhere on our SharePoint server. Right now, I\'m doing this with IE but I\'d like to automate t

6条回答
  •  温柔的废话
    2020-12-30 04:00

    I think my approach might help you.

    Initially i have created sharepoint account and followed the procedure in this link (http://www.ktskumar.com/2017/01/access-sharepoint-online-using-postman/) to get needed credentials for REST API's. once i got the credentials all i needed was the following dependency and code:

    
            org.apache.httpcomponents
            httpclient
            4.5
    
    

    Since i used OAUTH2 authentication, the code to get access token helps for other CRUD operations.

    /* OAuth2 authentication to get access token */
    public String getSharePointAccessToken() throws ClientProtocolException, IOException
    {
        /* Initializing variables */
        String grant_type = RcConstants.GRANT_TYPE;
        String client_id = RcConstants.CLIENT_ID;
        String client_secret = RcConstants.CLIENT_SECRET;
        String resource = RcConstants.RESOURCE;
        String url = RcConstants.OAUTH_URL + RcConstants.URL_PARAMETER + "/tokens/OAuth/2";
    
        /*
         * NOTE: RcConstants.OAUTH_URL =
         * https://accounts.accesscontrol.windows.net/ RcConstants.URL_PARAMETER
         * = Bearer Realm from
         * (http://www.ktskumar.com/2017/01/access-sharepoint-online-using-
         * postman/) Figure 6.
         */
    
        /* Building URL */
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    
        /* Adding URL Parameters */
        List urlParameters = new ArrayList();
        urlParameters.add(new BasicNameValuePair("grant_type", grant_type));
        urlParameters.add(new BasicNameValuePair("client_id", client_id));
        urlParameters.add(new BasicNameValuePair("client_secret", client_secret));
        urlParameters.add(new BasicNameValuePair("resource", resource));
        post.setEntity(new UrlEncodedFormEntity(urlParameters));
    
        /* Executing the post request */
        HttpResponse response = client.execute(post);
        logger.debug("Response Code : " + response.getStatusLine().getStatusCode());
    
        String json_string = EntityUtils.toString(response.getEntity());
        JSONObject temp1 = new JSONObject(json_string);  
        if (temp1 != null)
        {
            /* Returning access token */
            return temp1.get("access_token").toString();
        }
        return RcConstants.OAUTH_FAIL_MESSAGE;
    }
    

    Once we get access token we can upload using following method:

    public String putRecordInSharePoint(File file) throws ClientProtocolException, IOException
    {
        /* Token variable declaration */
        String token = getSharePointAccessToken();
        /* Null or fail check */
        if (!token.equalsIgnoreCase(RcConstants.OAUTH_FAIL_MESSAGE))
        { 
            /* Upload path and file name declaration */
            String Url_parameter = "Add(url='" + file.getName() + "',overwrite=true)";
            String url = RcConstants.UPLOAD_FOLDER_URL + Url_parameter;
            /*
             * NOTE: RcConstants.UPLOAD_FOLDER_URL =
             * https://.sharepoint.com/_api/web/
             * GetFolderByServerRelativeUrl('/Shared%20Documents/')/
             * Files/
             */
    
            /* Building URL */
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Authorization", "Bearer " + token);
            post.setHeader("accept", "application/json;odata=verbose");
            /* Declaring File Entity */
            post.setEntity(new FileEntity(file));
    
            /* Executing the post request */
            HttpResponse response = client.execute(post);
            logger.debug("Response Code : " + response.getStatusLine().getStatusCode());
    
            if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()|| response.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value())
            {
                /* Returning Success Message */
                return RcConstants.UPLOAD_SUCCESS_MESSAGE;
            }
            else
            {
                /* Returning Failure Message */
                return RcConstants.UPLOAD_FAIL_MESSAGE;
            }
        }
        return token;
    }
    

提交回复
热议问题