Skip to Content

Overview:

Here we will see

  • Using SAP-PI UDF (Java), we consume SharePoint REST to write a File into SharePoint.
  • A business requirement, where employee’s pending item counts need to be updated in SharePoint in file format.
  • Employee’s Pending Count will be fetched from one system’s REST service and resulted string will be posted into a file format in SharePoint.
  • Fetching Employee’s Pending Count via respective REST service will be handled in separate UDF-1 and its result will be supplied to this SharePoint UDF-2.
  • Here we focus on java coding of “SharePoint UDF-2”
  • To access SharePoint, we need to fetch AccessToken first which can be get by following link help:

 

JavaCode to Create a file in SharePoint:

  • Here we try to write a constant string into SharePoint in FileFormat
  • This constant string can be replaced by desired strings like employee’s pendingCount data as described in Overview section
  • AccessToken required for SharePoint authentication which can be found from above mentioned link.
/*
  Sharepoint REST details to create a file:
  url: http://<siteUrl>/_api/web/GetFolderByServerRelativeUrl('/<FolderName>')/Files/add(url='<fileName>',overwrite=true)
  method: POST
  headers:
      Authorization: "Bearer " + accessToken			
  body: "Contents of file"
*/

  //Frame Sharepoint REST URL to create a File
  String siteURL = "https://<host>/<siteURL_path>";	//here <siteURL_path> is '/teams/SPdev/AlertsCount'	
  String wsUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files/add(url='File1.txt',overwrite=true)";	

  //Data to be written in File			
  String request = "Create a File with raw string !!!";
				
  //Create HttpURLConnection
  URL url = new URL(wsUrl);
  URLConnection connection = url.openConnection();
  HttpURLConnection httpConn = (HttpURLConnection) connection;
			
  //Set Header
  httpConn.setDoOutput(true);
  httpConn.setDoInput(true);	
  httpConn.setRequestMethod("POST");				
  httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);

  //Send Request
  DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream ());
  wr.writeBytes(request);
  wr.flush();
  wr.close();
				
  //Read the response.
  String responseStr = "";
  if (httpConn.getResponseCode() == 200) {
    responseStr = "File has been written successfully. ResponseCode: "+ httpConn.getResponseCode();
  }else{
    responseStr += "Error while writing file, ResponseCode: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage();
  }	
  
  //System.out.println(httpResponseStr);	//Print response
	

 

Testing Status in SharePoint:

 

 

Blog updated on 24-Jul2018 with following contents:

Lets see how we can read files present in some specific folder in SharePoint.

Here, in following examples, we will read files from default folder ‘Documents’ which while accessing referred as ‘Shared Documents’.

[1] JavaCode to retrieve all files of a folder from SharePoint:

/*
Sharepoint REST details to retrieve all of the files in a folder
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or "application/atom+xml"
*/
try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<siteURL_path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
   httpConn.setRequestProperty("accept", "application/json;odata=verbose"); //To get response in JSON
   //httpConn.setRequestProperty("accept", "application/atom+xml");         //To get response in XML
   
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 

[2] JavaCode to retrieve a specific file from SharePoint:

/*
Sharepoint REST details to retrieve a specific file
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files('file name')/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken
*/

try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files('XYZ.txt')/$value";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
  
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 

[3] JavaCode to retrieve a specific file from SharePoint when you know file’s URL:

/*
Sharepoint REST details to retrieve a file with its URL
url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name')/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken
*/

try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<siteURL_path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   //URL-Type-1
   String wsUrl = siteURL + "/_api/web/GetFileByServerRelativeUrl('/<siteURL_path>/Shared%20Documents/XYZ.txt')/$value";

   //URL-Type-2
   //String wsUrl = siteURL + "/_api/Web/GetFileByServerRelativePath(decodedurl='/<siteURL_path>/Shared%20Documents/XYZ.txt')/$value";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
  
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 


<<<<< Parent blog reference…..  Integrate SharePoint using SAP PI

To report this post you need to login first.

15 Comments

You must be Logged on to comment or reply to a post.

    1. Dilip Kumar KrishnaDev Pandey Post author

      Dear Former Member

      Sorry for delayed response, I was too much busy in my current project….

      This is working in PI 7.1 and PO 7.5.

      But I’ve not tried this in XI version, it should work because this is UDF logic to call REST service with POST method, jre1.4 too is supported with this piece of code.

       

      Thanks & Regards

      Dilip

       

      (0) 
  1. Antony FERMINUS

    Hi Dilip,

    Thanks for the blog.

    I get error HTTP ResponseCode: 404 Not Found.

    I have the token. The url is also correct. I use PO 7.5.

    Is it a kind of permission issue to upload the file?

     

    regards,

    Antony.

    (0) 
  2. vinay mittal

    Hi Guys ,

     

    I am stuck!, First of all thanks Dilip for such a wonderful blog. I am able to get the access token  by the client id/secret etc.

    I am calling this API 

    https://xxxx.sharepoint.com/_api/web/GetFileByServerRelativeUrl('/sites/hub/dept/COTraining/Wisam/Shared%20Documents/BushfireAreas.txt‘)/$value to read the file but it says File doesnt exist!

     

    am I doing some mistake in the url creation? Authentication works fine as i was getting a 200 OK on this dummy API request

    https://<sitename&gt;.sharepoint.com/_api/web?$select=Title

     

    Do i need to add some special permissions to the target sharepoint team site?

     

     

    (0) 
    1. Dilip Kumar KrishnaDeo Pandey Post author

      Hi,

      • Please cross verify if folder ‘Documents’ has same file in SharePoint.
      • As per your error, seems to be file not present at same location.
      • And no extra permission required, as your code is able to view the Folder.
      • And I am updating this blog too with File Read info for others benefit…….

       

      Thanks & Regards,

      Dilip

      (0) 
  3. anurag kumar

    Hi Dilip,

    1st of all thanks a lot !! for such a wonderful post.

    But I am getting error as –  Access denied. You do not have permission to perform this action or access this resource

    when I am trying to download a file .
    I am able passing the generated access token correctly(using client Id + secret ) . still I am getting access denied every time.

    ——————-
    but If I am trying to directly hit this url in browser (Google chrome)-

    siteURL+/_api/Web/GetFileByServerRelativePath(decodedurl=’/<siteURL_path>/Shared%20Documents/XYZ.txt’)/$value”

    file is getting downloaded . as browser has my share point username and password.
    But in your approach where we can pass our share point credential.
     

    (0) 
  4. anurag kumar

    Hi Dilip,

    If I trying upload using above post . I am getting response 200 (success) but I am not able to see the files in sharePoint .

    AS official doc says – https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/upload-a-file-by-using-the-rest-api-and-jquery

    do we need to use  jquery here ?
    or After calling upload method in java suggested by you in blog do we have to update File Metadata?
    do we have any way to set up-loader name (user name) or file id to share point ?

     

    (0) 
    1. Dilip Kumar KrishnaDev Pandey Post author

      Hi Anurag,

      If you are getting Response code 200 (success), you should see the files in SharePoint, please check correct directory which was given in URL.

      About other queries, please find following comments:

      1. No mandatory concept of using JQuery only, SharePoint REST-Services can be called from any Platform/Language which supports REST-API calls.
      2. No need to update any File Metadata.
      3. And about set up-loader name (user name) or file id to SharePoint
        • This you have to discuss with your SharePoint team.
        • Max you can provide your userName or FileID in FileNames only, next how SharePoint utilizes how it reads, its all dependent on SharePoint’s custom logic.
        • or if any std. mechanism is present, that you have to follow.
        • In my info, when file gets created in to SharePoint, SharePoint too assigns unique FileID to each FileName.

      Parallel if you are interested in sending ‘pdf’ files too in SharePoint, you should have a look on below blog:

       

      Thanks & Regards,

      Dilip

      (1) 
      1. anurag kumar

        I am checking it in correct directory only
        even If i am trying to list all the files in the directory where i uploaded the file ( named asFile1.txt same as above example) by a rest get  query –

        siteURL/_api/web/GetFolderByServerRelativeUrl('folder name')/files	

        in response i am able to see the uploaded file
        but there in response JSON two properties are null or empty –  “LinkingUri”: null, && “LinkingUrl”: “”
        I suspect this may be a reason why my uploaded file is not visible in share point website . because other file what I see in share point those have “LinkingUri”: ‘correct_url’, && “LinkingUrl”: “correct_url”   they are not empty .

        "CheckInComment": "",
        "CheckOutType": 0,
        "ContentTag": "{#someText},1,1",
        "CustomizedPageStatus": 0,
        "ETag": "\"{#someText},1\"",
        "Exists": true,
        "IrmEnabled": false,
        "Length": "42",
        "Level": 255,
        "LinkingUri": null,
        "LinkingUrl": "",
        "MajorVersion": 0,
        "MinorVersion": 1,
        "Name": "File1.txt",
        "ServerRelativeUrl": "/abc/xyz/folder name/File1.txt",
        "TimeCreated": "2018-11-01T08:19:17Z",
        "TimeLastModified": "2018-11-01T08:19:17Z",
        "Title": null,
        "UIVersion": 1,
        "UIVersionLabel": "0.1",
        "UniqueId": "#someText"

        do we have to post these two field properties : –

        "LinkingUri" && "LinkingUrl"

        from java code  in out post request?

        (0) 
        1. Dilip Kumar KrishnaDev Pandey Post author

          Hi Anurag,

          No, you don’t have to provide “LinkingUri” && “LinkingUrl” in REST-File-POST code, only File content (String) and respective REST-URL required.

          Can you provide your code here, which you are trying for File POST in SharePoint ?

           

          Thanks & Regard,

          Dilip

          (1) 
          1. anurag kumar

            it’s exactly same as code posted by you…

            	public static void upload(String source){
            		//here I am passing source as 
            		//https://myOrganizationUrl/sites/abc/_api/web/GetFolderByServerRelativeUrl('xyz')/Files/add(url='testFile.txt',overwrite=true)
            		//while calling this method
            		URL url = new URL(source);
            		URLConnection connection = url.openConnection();
            		HttpURLConnection httpConn = (HttpURLConnection) connection;
            
            		// Set Header
            		httpConn.setDoOutput(true);
            		httpConn.setDoInput(true);
            		httpConn.setRequestMethod("POST");
            		String accessToken = getSharePointAccessToken();// method to get token
            		httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
            
            		// Send Request
            		DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
            		// Data to be written in File
            		String testString = "Create a File with raw string !!! Test";
            		wr.writeBytes(testString);
            		wr.flush();
            		wr.close();
            
            		// Read the response.
            		String responseStr = "";
            		if (httpConn.getResponseCode() == 200) {
            			responseStr = "File has been written successfully. ResponseCode: " + httpConn.getResponseCode();
            		} else {
            			responseStr += "Error while writing file, ResponseCode: " + httpConn.getResponseCode() + " "
            					+ httpConn.getResponseMessage();
            		}
            		
            		System.out.println("upload Response :  "+ responseStr);
            	}
            (0) 
            1. Dilip Kumar KrishnaDev Pandey Post author

              Hi Anurag,

              • Code is fine.
              • Can you just try to 1st write a file in default directory ‘Documents’ using //*///_api/web/GetFolderByServerRelativeUrl(‘Shared%20Documents’)//*
              • If you can see file in this directory, then there may be some display/read permission issue with your directory.

               

              Regards,

              Dilip

              (1) 

Leave a Reply