how to get a file from shrepoint using java code example

Example: get a document from sharepoint from java

/*
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());
}

Tags:

Java Example