RSS

Connecting to SharePoint 2013 online (365) API’s in Android

18 Jul

I decided to write a post about this because I had a lot of trouble until I make it work.

And this was my first Android App 😦 .

I googled a lot trying to connect, first I tried to get data from SharePoint using API’s which then I had problems in authentication my connection then after I get data successfully I said ok I will post data successfully too.

And what you think happen, will it wasn’t a successful first try, I had another security errors.

So I had this mad week trying to collect the pieces from all the articels and posts. and voala it worked. And really I didn’t find a one place that have every thing in details that helped me, so I decided to do it and post this detailed code for every thing to connect.

So first thing first, you need to know that to connect to SharePoint 365 you need to login to it to get some cookies that will allow you to connect to SharePoint API’s.

So you need to create an activity that contains a webview control that will load your SharePoint site.

Then in the java file in onCreate function you add those lines of code:

WebView webView = (WebView) findViewById(R.id.webView_Sharepoint_Login);

webView.loadUrl("https://yoursite.sharepoint.com");

webView.getSettings().setJavaScriptEnabled(true);

CookieManager.getInstance().removeSessionCookie();

So this first block of code you are making a reference to the WebView Control that you added in the layout file, then telling it to load your SharePoint site and to enable JavaScript. Then you remove all existence Cookies.

Then you need to override “shouldOverrideUrlLoading”

webView.setWebViewClient(new WebViewClient(){
@Override
public Boolean shouldOverrideUrlLoading(WebView view, String url) {
}

in it you will put the below code:

view.loadUrl(url);
CookieManager cookieManager = CookieManager.getInstance();
String Cookies = cookieManager.getCookie("https://yoursite.sharepoint.com/SitePages/Home.aspx?AjaxDelta=1");

Here you get an instance from Cookie Manager and telling him to get cookies from any URL you want inside your SharePoint site.

if(Cookies.contains("rtFa"))
{
String[] seperated = Cookies.split(";");
boolean RTFA = false;
boolean FedAuth = false;
String RTFA_Value = "";
String FedAuth_Value = "";
for(int i=0;i <= seperated.length - 1;i++)
{
if(seperated[i].contains("rtFa") && RTFA != true)
{
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(SharePointActivity.this);
SharedPreferences.Editor editor = shared.edit();
RTFA_Value = seperated[i].substring(6);
editor.putString("rtFa", RTFA_Value);
editor.commit();
RTFA =true;
}
if(seperated[i].contains("FedAuth") && FedAuth != true)
{
SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(SharePointActivity.this);
SharedPreferences.Editor editor = shared.edit();
FedAuth_Value = seperated[i].substring(9);
editor.putString("FedAuth", FedAuth_Value);
editor.commit();
FedAuth =true;
}
if(RTFA == true && FedAuth == true)
{
finish();
}}}

In the above code I loop throw all the split string array values and check if it contains “rtFa” and “FedAuth” then create a shared preferences and put the value there, so I maintain these value in this way.

If the two Booleans are true then finish the activity, this will send you back to the previous activity.

You end your override with return true cause it needs something to return.

This will end the login to SharePoint part.

Now lets start the actual work:

First of all you need to put you code in an AsyncTask class, or it will give you a network error.

Now lets get to the code it self:

SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
String RTFA = shared.getString("rtFa", "No Value");
String FedAuth = shared.getString("FedAuth", "No Value");

So we need to get our Cookies values that we get in the login activity.

DefaultHttpClient httpclient = new DefaultHttpClient();

Then we define a DefaultHttpClient to use it to execute our HttpGet or HttpPost methods.

Lets start with a Get method:

HttpGet httpGet = new HttpGet("https://YourSite.sharepoint.com/_api/lists/getbytitle('Android_Tasks')/items");

httpGet.addHeader("Cookie","rtFa=" + RTFA + "; FedAuth=" + FedAuth);

httpGet.setHeader("Accept","application/json;odata=verbose");

httpGet.setHeader("Content-type","application/json;odata=verbose");

HttpResponse response = httpclient.execute(httpGet);

The response will be a json with all items in “Android_Tasks” list.

That’s it for Get , now lets see the Post method.

Its almost like Get but the new thing here that you want to get a value “FormDigestValue” from another api first called “ContextInfo”.

Lets see the code :

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(https://YourSite.sharepoint.com/_api/contextinfo");

I want to say something here before I continue the code, you may be wondering why I used a Post method even though we want to get a value, will this is explained by that this api don’t accept a get method it accepts a post for security as I understood.

Lets continue 🙂 :

httpPost.addHeader("Cookie", "rtFa=" + RTFA + "; FedAuth=" + FedAuth);
httpPost.setHeader("Accept", "application/json;odata=verbose");
httpPost.setHeader("Content-type","application/json;odata=verbose");
// This Response Handler is used so we get all the response in string format
ResponseHandler responseHandler = new ResponseHandler() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return EntityUtils.toString(response.getEntity());
}};
// Executing the POST method
String response = httpclient.execute(httpPost, responseHandler);
// Converting the returned response string to json object
// Then getting the first json object in the response
JSONObject jsonObj = new JSONObject(response).getJSONObject("d");
// Then getting the second json object
JSONObject jsonObj2 = jsonObj.getJSONObject("GetContextWebInformation");
// Then we can access to the value that we want
String FormDigestValue = jsonObj2.getString("FormDigestValue");
// This is the main POST method that we will create an item in task list using it
HttpPost httpPost2 = new HttpPost("https://YourSite.sharepoint.com/_api/lists/getbytitle('Android_Tasks')/items");
// Adding headers to it with the Request Digest that we get from the previous POST method
// with the Cookie's too to be authorized
httpPost2.setHeader("Accept", "application/json;odata=verbose");
httpPost2.setHeader("Content-type","application/json;odata=verbose");
httpPost2.setHeader("X-RequestDigest", FormDigestValue);
httpPost2.addHeader("Cookie", "rtFa=" + RTFA + "; FedAuth=" + FedAuth);
// Building our json body
// For reference the value SP.Data.Android_x005f_TasksListItem
// you get it by adding
// your sharepointsite/_api/lists/getbytitle('Android_Tasks')?$select=ListItemEntityTypeFullName
String js = "{'__metadata':{'type':'SP.Data.Android_x005f_TasksListItem'},'Title':'" + TaskName + "','Body':'" + Description + "'}";
// Adding the json body to the POST method
httpPost2.setEntity(new StringEntity(js));
// Executing it to create the item

String response2 = httpclient.execute(httpPost2,responseHandler);

That’s it, when the execute is done if you refresh your task list you should see a new task there.

Hope this help every body :).

 
10 Comments

Posted by on July 18, 2013 in Android

 

Tags: , , , , , ,

10 responses to “Connecting to SharePoint 2013 online (365) API’s in Android

  1. Ken

    September 3, 2013 at 2:05 am

    I was new too and would like to know if I can download your java code to make connection to Sharepoint?

     
    • asheshany

      October 27, 2013 at 7:18 am

      sorry Ken for this sooo late response.
      About the java code , sorry I cant provide it to you , but you can take the code snippets from the post.

       
  2. Keriackus

    October 22, 2013 at 11:52 am

    Important Notes:
    -use trim() before subString
    -replace subString(6) with subString(5);
    -replace subString(9) with subString(8);

     
    • asheshany

      October 27, 2013 at 7:22 am

      Thanks for your comment

       
  3. samraj

    October 24, 2013 at 10:57 am

    Is this working for u now??

     
    • asheshany

      October 27, 2013 at 7:25 am

      sorry samraj for my late response , it was working for me when I wrote the post. I didn’t check it again.

       
      • samraj

        October 28, 2013 at 1:15 pm

        Thanks, Actually you are opening the Web view for authentication. I need to do with the stand alone java program without opening any browser

         
      • asheshany

        October 29, 2013 at 6:28 am

        I actually tried that before I go for the web view and I couldn’t make it happen.

         
  4. Calin

    October 25, 2013 at 9:21 am

    Hello asheshany.
    I want to ask you for a little favour. I`m new to android, and i`m having some difficulties setting up the code properly.
    Could you please make a package with the project, sources, and everything needed for this sample to work properly?

    Thank you very much!
    Kind regards,
    Calin.

     
    • asheshany

      October 27, 2013 at 7:38 am

      Dear Calin,
      Sorry but I cant provide a package.
      The goal of my post was to show how to connect to SharePoint 365 api’s.
      The first important thing is to get the authorization, then to use the Get Or Post methods.

       

Leave a comment