Java Sharepoint Rest Api Write File Example

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:
    • SharePoint REST to Get AccessToken using SAP-PI UDF: [Part-1]

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 filefrom 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 filefrom 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

learytogeres.blogspot.com

Source: https://blogs.sap.com/2018/02/01/consume-sharepoint-rest-to-create-a-file-using-java-sap-pi-udf/

0 Response to "Java Sharepoint Rest Api Write File Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel