Java Urlconnection Post Upload File to Sharepoint Document Library
Skip to content
Uncategorized
Java lawmaking to Download files using sharepoint APIs
Agenda :
- Generate Admission 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 y'all people must accept read already in my previous blog. Pasting the link again for your revision.
Now you lot know the complete process of generating the client ID and Client underground ID so use the below code to generate the access token.
public static String getSharepointToken() throws IOException { /** * This office helps to get SharePoint Admission Token. SharePoint Access * Token is required to authenticate SharePoint Rest service while * performing Read/Write events. SharePoint Residuum-URL to go access token * is as: https://accounts.accesscontrol.windows.net/ * /tokens/OAuth/2 * * Input required related to SharePoint are every bit: 1. shp_clientId ii. * shp_tenantId 3. shp_clientSecret */ Cord accessToken = ""; endeavor { // 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", "awarding/x-world wide web-course-urlencoded"); httpConn.setDoOutput(true); httpConn.setDoInput(truthful); httpConn.setRequestMethod("Mail"); 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.shut(); // Read the response. InputStreamReader isr = naught; 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\":\"") > -i) { int i1 = outputString.indexOf("access_token\":\""); String str1 = outputString.substring(i1 + xv); int i2 = str1.indexOf("\"}"); Cord str2 = str1.substring(0, i2); accessToken = str2; // System.out.println("accessToken.........." + accessToken); } } catch (Exception e) { accessToken = "Error: " + e.getMessage(); } render accessToken; } Few words or phrases used in higher up code are as follows.
- <your organization here> is "Origanisations's Sharepoint Host" for instance if your organization'due south proper 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 web log link http://gotobo.in/sharepoint-grime/
- <shp_clientSecret> is "Your surreptitious Id which you have generated, for more than on this read my previous blog link http://gotobo.in/sharepoint-grime/
- <shp_tenantId> – Yous tin can get the the Tenant ID from the Azure Active Directory admin center. Navigate to https://aad.portal.azure.com/ and the select Azure Agile Directory in the left navigation. The Overview page displays the Tenant ID.
For any dubiousness on share point token generation practice write in comments below i will help you out. Enjoy coding.
Beneath is my code to download files once yous have generated the access token using client ID, Client Secret and Tenant ID above.
//DOWNLOAD attempt { String accessTokenInt = getSharepointToken(); Cord accessTokenIntglobal=accessTokenInt; System.out.println("Access Token Generated - "+accessTokenIntglobal); //Beneath folderUrl is the directory from where we will download the file. //and SiteURL is organizations' site for e.thou. gotobo.sharepoint.com/sites/mysite Cord folderUrl = "Shared%20Documents"+"/test"; Cord siteURL = "https://gotobo.sharepoint.com/sites/mysite"; // ====================================================================== // Go Folder Names from share point site to match our required directory from where download operation will be performed // ====================================================================== String fUrl0 = siteURL + "/_api/spider 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"); Cord httpFResponseStr0 = ""; InputStreamReader fisr0 = nix; 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()) != goose egg) { httpFResponseStr0 = httpFResponseStr0 + strfLine0; System.out.println("strfLine==" + strfLine); } System.out.println(httpFResponseStr0); // Print Cord 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 exist downloaded // ====================================================================== String fUrl = siteURL + "/_api/spider 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("Say-so", "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", "%xx"); 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("Go"); httpfConn.setRequestProperty("Authorisation", "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("%xx", " "); 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(); Organization.out.println(fileName + " downloaded :"); if(fileName.length()==0) { filelink="File non found"; } else { filelink= "file is found"; } } } } catch (Exception eastward) { eastward.printStackTrace(); System.out.println("The file could not be downloaded/Token error/File IO : "+new Timestamp(Organisation.currentTimeMillis())); filelink="File not found"; } Guys do permit me know for any doubt in comments section. Upload part is done, see you at download operation using Share Betoken API.
Source: http://gotobo.in/java-code-to-download-files-using-sharepoint-apis/
0 Response to "Java Urlconnection Post Upload File to Sharepoint Document Library"
Postar um comentário