Export (0) Print
Expand All

Open the OneNote clients with the OneNote API

Learn how to open the OneNote desktop and online clients using URLs returned by the Microsoft OneNote API.

Last modified: April 18, 2014

Applies to: OneNote service

In this article
Opening OneNote from an Android app
Opening OneNote from an iOS app
Opening OneNote from a Windows Phone app
Opening OneNote from a Windows Store app

When your app performs a successful POST to the OneNote API pages collection at https://www.onenote.com/api/v1.0/pages, the API returns a status code and a pair of URLs in a Json object. Those URLs both point to the new page, and differ in whether they open the native or online OneNote client. The following code shows how the status code and links appear in the HTTP response.


201
{
"links" :
  {
    "oneNoteClientUrl" : {"href" : "onenote:https://..."},
    "oneNoteWebUrl" : {"href" : "https://..."}
  }
}

Of course, the URLs are longer than shown above. The main difference in the values is that the native client URL, oneNoteClientUrl includes the "onenote" prefix to the https protocol identifier.

The oneNoteWebUrl can be used on any of the client platforms to open the OneNote Online client, as long as the default browser on the device is compatible with the OneNote Online client.

To open an already-installed OneNote native client on the device, use the oneNoteClientUrl. On Windows Phone and Android devices, modify the oneNoteClientUrl value to add braces {…} around the GUIDs. We've provided some code samples that show how to do that in the following platform-specific sections.

The general flow after your POST is to check the HTTP status result, and use a Json parser to get the URLs. Then, use the appropriate URLs to open the client.

OneNote native and online clients are available in many languages. When your app opens a OneNote Online client, the browser language setting determines which OneNote client language appears. When your app opens a native client, the platform language setting is used, or if there's a language-specific OneNote version installed, that's what will open.

In addition to the HTTP response status code and URLs, the OneNote API returns an X-header containing a "correlation ID". This ID might be needed when you're working with Microsoft support to troubleshoot problems between your app, the API, and a user's OneNote notebook. For more information, see Debug and handle errors with the OneNote API.

Our samples all use third-party Json libraries, and we've provided links to them in each of the following sections and collected them in the Get tools and libraries to use with the OneNote API topic. The following code is taken directly from the samples we've posted on GitHub. For more information, see Get the OneNote API sample applications.

TipTip

These samples should not be considered production-ready code. Things like detailed user-input validation have been left out to make it easier to understand the code flow. Carefully review your code for potential code-quality and security issues before you publish your app.

The following code gets the URLs from the Json status response. It uses the Google GSON library (http://code.google.com/p/google-gson/) to extract the two URLs. In the following, mUrlConnection is the HttpsURLConnection object used to make the POST request to the OneNote API. The response object is an instance of a class defined in your code to store the response property values.

This code is available for download as part of the Android code sample on GitHub. For more information, see Get the OneNote API sample applications.


public ApiResponse getResponse() throws Exception {
   /* Retrieve the HTTP response code and message from the connection object */
   int responseCode = mUrlConnection.getResponseCode();
   String responseMessage = mUrlConnection.getResponseMessage();
   String responseBody = null;

   /* Verify that the new page was created successfully, 
      with HTTP status = 201 */
   if ( responseCode == 201) {
      InputStream is = mUrlConnection.getInputStream();

      /* Verify that this byte array is big enough */
      byte[] b1 = new byte[1024];
      StringBuffer buffer = new StringBuffer();

      /* Copy the body of the response into the new string */
      /* again, make sure the buffer is big enough! */
      while ( is.read(b1) != -1)
         buffer.append(new String(b1));

      /* When the returned data is complete, close the connection 
         and convert the byte array into a string */
      mUrlConnection.disconnect();
      responseBody =  buffer.toString();
   }

   /* Create a new Json object, and an object to hold the response URLs */
   JSONObject responseObject = null;
   ApiResponse response = new ApiResponse();
   try {

      /* Store and verify the HTTP response code */
      response.setResponseCode(responseCode);
      response.setResponseMessage(responseMessage);
      if ( responseCode == 201) {

         /* Create the object and retrieve the two URLs */
         responseObject = new JSONObject(responseBody);
         String clientUrl = responseObject.getJSONObject(
            "links").getJSONObject("oneNoteClientUrl").getString("href");
         String webUrl = responseObject.getJSONObject(
            "links").getJSONObject("oneNoteWebUrl").getString("href");
         response.setOneNoteClientUrl(clientUrl);
         response.setOneNoteWebUrl(webUrl);
      }
   } catch (JSONException ex) {

      /* If the Json was malformed or incomplete... */
      String msg = ex.getMessage();
      msg = msg;
   }
   return response;
}

Then, using those response object properties, your app can open the OneNote Online client shown in the following code.


if (response.getReseponseCode() == 201) {
    Uri uriUrl = Uri.parse(response.getOneNoteWebUrl);  
    Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); 
    startActivity(launchBrowser);
}

When using the oneNoteClientURL to open the native OneNote client on an Android device, your code must surround the GUID strings with braces {…} before starting the Intent. The following code shows how to do that.


if (response.getReseponseCode() == 201) {
   // Get the URL from the OneNote API JSON response
   String onenoteClientUrl = obtainClientLinkFromJSONResponse();
   String androidClientUrl = 
      onenoteClientUrl.replaceAll(
      "=([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})&",
      "={$1}&");
  // Open the URL: Open the newly created OneNote page
  Uri uriUrl = Uri.parse(androidClientUrl);  
  Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl); 
  startActivity(launchBrowser);
}

The following code gets the URLs from the Json status response. It uses the AFNetworking library (http://afnetworking.com/) to extract the two URLs. In the following, created is a pointer to the ONSCPSStandardResponse object used to store the response values, and responseObject holds the parsed Json.

This code is available for download as part of the iOS code sample on GitHub. For more information, see Get the OneNote API sample applications.


/* Import the Json library */
#import "AFURLRequestSerialization.h"

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  if(delegate) {
    int status = [returnResponse statusCode];
    ONSCPSStandardResponse *standardResponse = nil;
    if (status == 201) {
      ONSCPSCreateSuccessResponse *created = 
        [[ONSCPSCreateSuccessResponse alloc] init];
      created.httpStatusCode = status;
      NSError *jsonError;
      NSDictionary *responseObject = 
        [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
      if(responseObject && !jsonError) {
        created.oneNoteClientUrl = ((NSDictionary *)
          ((NSDictionary *)responseObject[@"links"])[@"oneNoteClientUrl"])[@"href"];
        created.oneNoteWebUrl = ((NSDictionary *)
          ((NSDictionary *)responseObject[@"links"])[@"oneNoteWebUrl"])[@"href"];                }
        standardResponse = created;
    }
    else {
      ONSCPSStandardErrorResponse *error = [[ONSCPSStandardErrorResponse alloc] init];
      error.httpStatusCode = status;
      error.message = [[NSString alloc] initWithData:returnData 
        encoding:NSUTF8StringEncoding];
      standardResponse = error;
    }
    // Send the response back to the client.
    if (standardResponse) {
      [delegate exampleServiceActionDidCompleteWithResponse: standardResponse];
    }
  }
}

Now that you've extracted the URLs from the response, use them to open the OneNote client, using the following code. Use the oneNoteClientUrl to open the installed native OneNote app, or the oneNoteWebURL to open a OneNote Online client.


NSURL *url = [NSURL URLWithString:standardResponse.oneNoteWebUrl];
[[UIApplication sharedApplication] openURL:url];

The following method gets the URLs from the Json status response. It uses the Newtonsoft Json.net library (http://json.codeplex.com/) to extract the two URLs. In this code, response is the object returned by the HTTPS POST. Depending the whether the POST succeeds, standardResponse is an object created as either a CreateSuccessResponse or StandardErrorResponse, which are classes defined elsewhere in the download sample.

This code is available for download as part of the Windows Phone 8 code sample on GitHub. For more information, see Get the OneNote API sample applications.

        
private async static Task<StandardResponse> 
  TranslateResponse(HttpResponseMessage response)
{
  StandardResponse standardResponse;
  if (response.StatusCode == HttpStatusCode.Created)
    {
      dynamic responseObject = 
        JsonConvert.DeserializeObject(await 
        response.Content.ReadAsStringAsync());
      standardResponse = new CreateSuccessResponse
        {
          StatusCode = response.StatusCode,
          OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
          OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
        };
    }
    else
    {
      standardResponse = new StandardErrorResponse
        {
          StatusCode = response.StatusCode,
          Message = await response.Content.ReadAsStringAsync()
        }; 
    }
}

The following code opens the Windows Phone OneNote Online client using the extracted oneNoteWebUrl.


  Windows.System.Launcher.LaunchUriAsync(new Uri(standardResponse.OneNoteWebUrl));

When using the oneNoteClientUrl on a Windows Phone device, surround the GUID strings with braces {…} before calling LaunchUriAsync. The following code shows how to use a regular expression to add those braces, and then open the OneNote native client.


  Regex guidRegex = 
    new Regex(@"=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})&",
  RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
  var matches = guidRegex.Matches(standardResponse.OneNoteClientUrl);
  if (matches.Count == 2)
  {
    standardResponse.OneNoteClientUrl = 
      standardResponse.OneNoteClientUrl.Replace(matches[0].Groups[1].Value, 
      "{" + matches[0].Groups[1].Value + 
      "}").Replace(matches[1].Groups[1].Value, 
      "{" + matches[1].Groups[1].Value + "}");
  }
  Windows.System.Launcher.LaunchUriAsync(
    new Uri(standardResponse.OneNoteClientUrl));

Windows Store app code is essentially the same as the Windows Phone app.

The following method gets the URLs from the Json status response. It uses the Newtonsoft Json.net library (http://json.codeplex.com/) to extract the two URLs. In this code, response is the object returned by the HTTPS POST. Depending the whether the POST succeeds, the code creates a standardResponse that is either a CreateSuccessResponse or StandardErrorResponse. Those classes are defined elsewhere in the downloadable sample.

This code is available for download as part of the Windows Store code sample on GitHub. For more information, see Get the OneNote API sample applications.

        
private async static Task<StandardResponse> 
    TranslateResponse(HttpResponseMessage response)
{
  StandardResponse standardResponse;
  if (response.StatusCode == HttpStatusCode.Created)
    {
      dynamic responseObject = 
        JsonConvert.DeserializeObject(await 
        response.Content.ReadAsStringAsync());
      standardResponse = new CreateSuccessResponse
        {
          StatusCode = response.StatusCode,
          OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
          OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
        };
    }
    else
    {
      standardResponse = new StandardErrorResponse
        {
          StatusCode = response.StatusCode,
          Message = await response.Content.ReadAsStringAsync()
        };
    }
  return standardResponse;
}

The following code opens the Windows OneNote clients using the extracted URLs. You can use the same code with either oneNoteClientUrl to open the native client, or with oneNoteWebUrl to open the OneNote Online client.

Windows.System.Launcher.LaunchUriAsync(new Uri(standardResponse.OneNoteClientUrl));

Show:
© 2014 Microsoft