JAVA code to insert record in SharePoint List

Hi All,

Corporate companies like Infosys, IBM, TCS have all collaborated with Sharepoint to use its services. Sharepoint as we all know gives us a platform to do CRUD operations on a file. We can upload a file on sharepoint and share its link with anyone amongst the organization employees.

Now we can also create a list using sharepoint where users can add/delete/update records.

There comes the need for automation to do CRUD operations via a code. My earlier blogs were focused on uploading and downloading files to and fro Sharepoint Site. This blog is for adding a new record over a sharepoint list.

Now remember, to perform such operations over sharepoint list we first need to create Client ID and Secret ID for our Sharepoint site. To know how to create IDs please click the link below. Step by Step process is explained in the link below.

ONCE YOU HAVE CREATED CLIENT ID AND SECRET ID LETS TAKE A LOOK INTO THE CODE FOR SHAREPOINT LIST – INSERTING RECORDS
package in.gotobo.sharepoint;

import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedList;
import java.util.Map;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.XML;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class dataPushToSharepoint {

	public static void main(String[] args) throws IOException 
	{
		int id = pushDataToSharepoint();	
	}

	
	
			

	public static int pushDataToSharepoint() 
	{
		try
		{
			String api_page = "https://ericsson.sharepoint.com/sites/gotobo/_api/web/lists/getbytitle('samplelist')/items";
			JsonParser parser = new JsonParser();
			String accessToken = getSharepointToken();
			if(accessToken.isEmpty())
			{
				System.out.println("Not able to get the token, return");
				return -1;
			}
			JSONObject JObj = new JSONObject();
			JSONObject obj1 = new JSONObject();
			obj1.put("type","SP.Data.PayloadInfoListItem");
			JObj.put("__metadata",obj1);
			JObj.put("Name","Tobo");
			final String jsonStrng = JObj.toString();
			URL obj = new URL(api_page);
			HttpsURLConnection postConnection = (HttpsURLConnection) obj.openConnection();
			postConnection.setHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			});
			postConnection.setRequestMethod("POST");
			postConnection.setRequestProperty("Accept", "'application/json; odata=verbose");
			postConnection.setRequestProperty("Content-Type", "application/json; odata=verbose");
			postConnection.setRequestProperty  ("Authorization", "Bearer "+accessToken);
			postConnection.setConnectTimeout(20000); 
			postConnection.setDoOutput(true);
			OutputStream os = postConnection.getOutputStream();
			os.write(jsonStrng.getBytes());
			os.flush();
			os.close();
			int responseCode = postConnection.getResponseCode();
			System.out.println("POST request on sharepoint response code is "+responseCode);
			if ((responseCode) == 200 || (responseCode == 201)) 
			{ 
				BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
				String inputLine;
				StringBuffer responseString = new StringBuffer();

				while ((inputLine = in .readLine()) != null) {
					responseString.append(inputLine);
				}
				//System.out.println(responseString.toString());
				JSONObject jsonObj = XML.toJSONObject(responseString.toString());
				//System.out.println(jsonObj.toString());
				//JsonParser parser1 = new JsonParser();
				//JsonObject jsonObj = parser.parse(responseString.toString()).getAsJsonObject();
				JSONObject entry = (JSONObject) jsonObj.get("entry");
				JSONObject content = (JSONObject) entry.get("content");
				JSONObject content1 = (JSONObject) content.get("m:properties");

				int retcode = (int) ((JSONObject)content1.get("d:ID")).get("content");		
				return retcode;
			}
			else
				System.out.println("POST FAILED");

		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception while pushing data to Sharepoint"+e.getMessage());
		}
		return -1;
	}


	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/
		 * <tenantID>/tokens/OAuth/2
		 * 
		 * Input required related to SharePoint are as: 1. shp_clientId 2.
		 * shp_tenantId 3. shp_clientSecret
		 * Tobo's Point
		 */

		String accessToken = "";
		try {

			// AccessToken url
			String wsURL = "https://accounts.accesscontrol.windows.net/92e84ceb-fbfd-47ab-be52-080c6b87953f/tokens/OAuth/2";
			String jsonParam = "grant_type=client_credentials"
					+ "&client_id=<fetch your client id and put here>@92e84ceb-fbfd-47ab-be52-080c6b8795"
					+ "&client_secret=<fetch your secret id and put here>"
					+ "&resource=00000003-0000-0ff1-ce00-000000000000/ericsson.sharepoint.com@92e84ceb-fbfd-47ab-be52-080c6b8795";

			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");
			// 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();
		}finally{
			//System.out.println("accessToken.........." + accessToken);
		}
		return accessToken;
	}


}


This is a working code. Remember to fetch your own client id and secret id and then feed in this code, put your sharepoint urls execute.

Happy Coding 🙂

4 thoughts on “JAVA code to insert record in SharePoint List

  1. Hello, Neat post. There is a problem with your web site in internet explorer,
    might check this? IE nonetheless is the marketplace leader and a large portion of folks will miss your excellent writing
    due to this problem.

  2. Excellent beat ! I wish to apprentice while you amend your web site, how
    could i subscribe for a blog web site? The account helped me a acceptable deal.
    I had been tiny bit familiar of this your broadcast offered brilliant clear idea

  3. I was suggested this blog by way of my cousin. I’m no longer certain whether or not this publish is written through him as nobody else recognize such detailed about my difficulty.
    You’re wonderful! Thanks!

Leave a Reply to our web hosting Cancel reply

Your email address will not be published.

Verified by MonsterInsights