Java code to upload files using sharepoint APIs

Agenda :

  • Generate Access token for share point
  • Upload file to share point on a specified path

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.

http://gotobo.in/sharepoint-crud/

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 upload files once you have genrated the access token using client ID, Client Secret and Tenant ID above.

try {
String accessTokenInt = getSharepointToken();
String siteURL = "https://gotobo.sharepoint.com/sites/";
//e.g. gotobo.sharepoint.com/sites/mysite
String folderUrl = "Shared%20Documents"+"/test";
//===============================================//
//Sharepoint API to create Path
//===============================================//
String url1w = siteURL + "/_api/web/GetFolderByServerRelativeUrl('"+folderUrl+"')";
System.out.println("The complete path is : " + url1w);
URL urlcw = new URL(url1w);
URLConnection con1 = urlcw.openConnection();
HttpURLConnection httpCon1 = (HttpURLConnection) con1;
httpCon1.setDoOutput(true);
httpCon1.setDoInput(true);
httpCon1.setRequestMethod("POST");
httpCon1.setRequestProperty("Authorization", "Bearer " + accessTokenInt);
DataOutputStream wr1 = new DataOutputStream(httpCon1.getOutputStream());
wr1.flush();
wr1.close();
// Read the response.
String respStr1 = "";
if (httpCon1.getResponseCode() == 200) {
respStr1 = "Path has been found/created successfully. ResponseCode : " + httpCon1.getResponseCode();
} else {
respStr1 += "Error while writing file, ResponseCode : " + httpCon1.getResponseCode() + " "+ httpCon1.getResponseMessage();
}System.out.println(respStr1);
//===============================================//
//Sharepoint API to upload file to Path
//===============================================//

try {
filePath=new File("c:/users/temp/abc.zip");
}catch(Exception nre)
{
System.out.println("User Cancelled the operation");
}
String filename = filePath.getName();
filename = filename.replaceAll("\s", "%20");

System.out.println(filename + " Selected for upload ");
String uploadlink = "";
uploadlink=siteURL+"/_api/web/GetFolderByServerRelativeUrl(\'"+ folderUrl+"/";
uploadlink = uploadlink+"\')/Files/add(url='" + filename + "',overwrite=true)";

executeMultiPartRequest(uploadlink,filePath);
System.out.println("File uploaded : "+uploadlink);
} catch (Exception e) {
e.printStackTrace();
System.out.println("The file could not be uploaded OR Token error");
}

You must have seen “executeMultiPartRequest” method used in above code. Below is the whole method.

public static void executeMultiPartRequest(String urlString, File file) throws IOException {
HttpPost postRequest = new HttpPost(urlString);
postRequest = addHeader(postRequest);
try {
postRequest.setEntity(new FileEntity(file));
//System.out.println("urlString :"+urlString);
} catch (Exception ex) {
ex.printStackTrace();
}
executeRequest(postRequest);
}

Other methods used in above snippet are as follow :

private static HttpPost addHeader(HttpPost httpPost) throws IOException {
//String accessTokenInt = getSharepointToken();
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.setHeader("Authorization", "Bearer " + accessTokenInt);
//System.out.println("httpPost…….." + httpPost);
return httpPost;
}
@SuppressWarnings({ "resource", "deprecation" })
private static void executeRequest(HttpPost httpPost) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
//System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

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

9 thoughts on “Java code to upload files using sharepoint APIs

  1. I think this is among the most significant info for me.
    And i am glad reading your article. But wanna remark on few general things, The website style is wonderful,
    the articles is really nice : D. Good job, cheers

  2. Attractive section of content. I simply stumbled
    upon your site and in accession capital to assert that I acquire actually enjoyed account your weblog posts.
    Any way I’ll be subscribing to your augment or even I achievement you get entry to constantly fast.

Leave a Reply to Casey Cancel reply

Your email address will not be published.

Verified by MonsterInsights