Java code to Download files using sharepoint APIs

Agenda :

  • Generate Access token for share point
  • Download file from share point on local machine

For generating the access token we need to use client ID and secret ID which you people must have read already in my previous blog. Pasting the link again for your revision.

Now you know the complete process of generating the client ID and Client secret ID so use the below code to generate the access token.

public static String getSharepointToken() throws IOException {
/**
* This function helps to get SharePoint Access Token. SharePoint Access
* Token is required to authenticate SharePoint REST service while
* performing Read/Write events. SharePoint REST-URL to get access token
* is as: https://accounts.accesscontrol.windows.net/
* /tokens/OAuth/2
*
* Input required related to SharePoint are as: 1. shp_clientId 2.
* shp_tenantId 3. shp_clientSecret
*/
String accessToken = "";
try {

    // AccessToken url

    String wsURL = "https://accounts.accesscontrol.windows.net/92e84ceb-fbfd-47ab-be52-080c6b87953f/tokens/OAuth/2";

    URL url = new URL(wsURL);
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;

    // Set header
    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");


    String jsonParam = "grant_type=client_credentials"
    + "&client_id=<shp_clientId>@<shp_tenandId>"
    + "&client_secret=<shp_clientSecret>"
    + "&resource=00000003-0000-0ff1-ce00-000000000000/<your organization here>.sharepoint.com@<shp_tenantId>";

   

    // Send Request
    DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
    wr.writeBytes(jsonParam);
    wr.flush();
    wr.close();

    // Read the response.
    InputStreamReader isr = null;
    if (httpConn.getResponseCode() == 200) {
        isr = new InputStreamReader(httpConn.getInputStream());
    } else {
        isr = new InputStreamReader(httpConn.getErrorStream());
    }

    BufferedReader in = new BufferedReader(isr);
    String responseString = "";
    String outputString = "";

    // Write response to a String.
    while ((responseString = in.readLine()) != null) {
        outputString = outputString + responseString;
    }
    // Extracting accessToken from string, here response
    // (outputString)is a Json format string
    if (outputString.indexOf("access_token\":\"") > -1) {
        int i1 = outputString.indexOf("access_token\":\"");
        String str1 = outputString.substring(i1 + 15);
        int i2 = str1.indexOf("\"}");
        String str2 = str1.substring(0, i2);
        accessToken = str2;
        // System.out.println("accessToken.........." + accessToken);
    }
} catch (Exception e) {
    accessToken = "Error: " + e.getMessage();
}
return accessToken;
}

Few words or phrases used in above code are as follows.

  • <your organization here> is “Origanisations’s Sharepoint Host” for example if your organization’s name is infosys then your organization’s sharepoint URL will be infosys.sharepoint.com
  • <shp_clientId> is “Your client Id which you have generated, for more on this read my previous blog link http://gotobo.in/sharepoint-crud/
  • <shp_clientSecret> is “Your secret Id which you have generated, for more on this read my previous blog link http://gotobo.in/sharepoint-crud/
  • <shp_tenantId> – You can get the the Tenant ID from the Azure Active Directory admin center. Navigate to https://aad.portal.azure.com/ and the select Azure Active Directory in the left navigation. The Overview page displays the Tenant ID.

For any doubt on share point token generation do write in comments below i will help you out. Enjoy coding.

?

Below is my code to download files once you have generated the access token using client ID, Client Secret and Tenant ID above.

//DOWNLOAD
            try {
		String accessTokenInt = getSharepointToken();
		String accessTokenIntglobal=accessTokenInt;
		System.out.println("Access Token Generated - "+accessTokenIntglobal);
		//Below folderUrl is the directory from where we will download the file. 
		//and SiteURL is organizations' site for e.g. gotobo.sharepoint.com/sites/mysite
		String folderUrl = "Shared%20Documents"+"/test";
		String siteURL = "https://gotobo.sharepoint.com/sites/mysite";
		// ======================================================================
		// Get Folder Names from share point site to match our required directory from where download operation will be performed
		// ======================================================================
		String fUrl0 = siteURL + "/_api/web/GetFolderByServerRelativeUrl(\'" + folderUrl+"/"
				+ "\')/Folders?$orderby=ListItemAllFields/Modified%20desc&$top=1";                            
		URL fileLstUrl0 = new URL(fUrl0);
		URLConnection fConnection0 = fileLstUrl0.openConnection();
		HttpURLConnection httpFConn0 = (HttpURLConnection) fConnection0;
		httpFConn0.setRequestMethod("GET");
		httpFConn0.setRequestProperty("Authorization", "Bearer " + accessTokenIntglobal);
		httpFConn0.setRequestProperty("accept", "application/json;odata=verbose");
		String httpFResponseStr0 = "";
		InputStreamReader fisr0 = null;
		if (httpFConn0.getResponseCode() == 200) {
			fisr0 = new InputStreamReader(httpFConn0.getInputStream());
		} else {
			fisr0 = new InputStreamReader(httpFConn0.getErrorStream());
		}
		BufferedReader fin0 = new BufferedReader(fisr0);
		String strfLine0 = "";
		while ((strfLine0 = fin0.readLine()) != null) {
			httpFResponseStr0 = httpFResponseStr0 + strfLine0;
			System.out.println("strfLine==" + strfLine);
		}
		System.out.println(httpFResponseStr0); // Print
		String fileName0 = "";
		JsonParser fparser0 = new JsonParser();
		JsonObject rootfObj0 = fparser0.parse(httpFResponseStr0).getAsJsonObject();
		JsonArray nameFileArray0 = rootfObj0.get("d").getAsJsonObject().get("results")
				.getAsJsonArray();
		for (JsonElement fpa : nameFileArray0) {
			JsonObject jsonFileNameObj = fpa.getAsJsonObject();
			fileName0 = jsonFileNameObj.get("Name").getAsString();
		}
		System.out.println(fileName0); // Print                         
		// ======================================================================
		// Get File Names to find our file to be downloaded
		// ======================================================================
		String fUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl(\'" + folderUrl+"/"
				 + "\')/Files?$orderby=ListItemAllFields/Modified%20desc";
		URL fileLstUrl = new URL(fUrl);
		URLConnection fConnection = fileLstUrl.openConnection();
		HttpURLConnection httpFConn = (HttpURLConnection) fConnection;
		httpFConn.setRequestMethod("GET");
		httpFConn.setRequestProperty("Authorization", "Bearer " + accessTokenIntglobal);
		httpFConn.setRequestProperty("accept", "application/json;odata=verbose");
		// Read the response
		String httpFResponseStr = "";
		InputStreamReader fisr = null;
		if (httpFConn.getResponseCode() == 200) {
			fisr = new InputStreamReader(httpFConn.getInputStream());
		} else {
			fisr = new InputStreamReader(httpFConn.getErrorStream());
		}
		BufferedReader fin = new BufferedReader(fisr);
		String strfLine = "";
		while ((strfLine = fin.readLine()) != null) {
			httpFResponseStr = httpFResponseStr + strfLine;
			System.out.println("strfLine==" + strfLine);
		}
		System.out.println(httpFResponseStr); // Print
		// response
		String fileName = "";
		JsonParser fparser = new JsonParser();
		JsonObject rootfObj = fparser.parse(httpFResponseStr).getAsJsonObject();
		JsonArray nameFileArray = rootfObj.get("d").getAsJsonObject().get("results")
				.getAsJsonArray();
		for (JsonElement fpa : nameFileArray) {
			JsonObject jsonFileNameObj = fpa.getAsJsonObject();
			fileName = jsonFileNameObj.get("Name").getAsString();
			//System.out.println("fileName :" + fileName);
			// ======================================================================
			// Download files in the
			// respective
			// folders
			// ======================================================================
			if(fileName.toString().toLowerCase().contains("gotobo.zip"))
			{
			fileName = fileName.replaceAll("\\s", "%20");
			String fileUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl(\'"
					+ folderUrl + "/" 
					+ "\')/Files('" + fileName + "')/$value";
			URL urlf = new URL(fileUrl);
			URLConnection fconnection = urlf.openConnection();
			HttpURLConnection httpfConn = (HttpURLConnection) fconnection;
			httpfConn.setRequestMethod("GET");
			httpfConn.setRequestProperty("Authorization", "Bearer " + accessTokenIntglobal);
			InputStream inputStream = httpfConn.getInputStream();
			String fileDir = "c:\\users\\gotobo\\";
			//System.out.println("My path : " + fileDir);
			File fileDirs = new File(fileDir);
			if (!fileDirs.exists()) {
				fileDirs.mkdirs();
			}
			fileName = fileName.replaceAll("%20", " ");
			String saveFilePath = "c:\\users\\gotobo\\"+fileName;;
			//System.out.println("saveFilePath.." + saveFilePath);
			FileOutputStream outputStream = new FileOutputStream(saveFilePath);
			int bytesRead = -1;
			byte[] buffer = new byte[1024];
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
			}

			outputStream.close();
			inputStream.close();

			System.out.println(fileName + "  downloaded :");
			if(fileName.length()==0)
			{
				filelink="File not found";
			}
			else
			{
				filelink= "file is found";
			}
		}
		}


        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println("The file could not be downloaded/Token error/File IO : "+new Timestamp(System.currentTimeMillis()));
            filelink="File not found";
        }   

Guys do let me know for any doubt in comments section. Upload part is done, see you at download operation using Share Point API.

7 thoughts on “Java code to Download files using sharepoint APIs

  1. After I originally commented I seem to have clicked on the
    -Notify me when new comments are added- checkbox and now every time a comment is added
    I get 4 emails with the exact same comment.

    There has to be a way you are able to remove me from that service?
    Appreciate it!

  2. Hey there! I could have sworn I’ve been to this blog
    before but after browsing through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely glad I found it and I’ll be bookmarking and checking back frequently!

  3. After I initially left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and
    from now on whenever a comment is added I receive four emails with the same comment.
    Perhaps there is an easy method you are able to remove me from that service?
    Thanks a lot!

Leave a Reply to Swati Cancel reply

Your email address will not be published.

Verified by MonsterInsights