Abrir o cliente do OneNoteOpen the OneNote client

Você pode usar a propriedade links de uma página ou de um bloco de anotações para abrir um aplicativo do OneNote em determinada página ou bloco de anotações.You can use the links property of a page or notebook to open a OneNote application to a particular page or notebook.

A propriedade links é um objeto JSON que contém duas URLs.The links property is a JSON object that contains two URLs. As URLs abrirão a página ou o bloco de anotações no aplicativo cliente do OneNote ou no OneNote na Web.The URLs will open the page or notebook in the OneNote client application or in OneNote on the web.

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

    • Abre o cliente do OneNote, caso já esteja instalado no dispositivo.Opens the OneNote client if it is already installed on the device. Essa URL inclui o prefixo onenote.This URL includes the onenote prefix.
    • Abre a versão de idioma específico, caso esteja instalada no dispositivo.Opens the language-specific version if one is installed on the device. Caso contrário, usa a configuração de idioma da plataforma.Otherwise, uses the platform language setting.
  • oneNoteWebUrloneNoteWebUrl

    • Abre o OneNote na Web se o navegador padrão no dispositivo oferecer suporte a ele.Opens OneNote on the web if the default browser on the device supports it.
    • Usa a configuração de idioma do navegador.Uses the browser language setting.

A API do OneNote retorna a propriedade links na resposta HTTP para as seguintes operações:The OneNote API returns the links property in the HTTP response for the following operations:

Os exemplos a seguir mostram como verificar o código de status da resposta, analisar o JSON para extrair as URLs e abrir o cliente do OneNote.The following examples show how to check the status code of the response, parse the JSON to extract the URLs, and then open the OneNote client.

Exemplo do iOSiOS example

O exemplo a seguir obtém as URLs de cliente do OneNote da resposta JSON.The following example gets the OneNote client URLs from the JSON response. Ele usa a biblioteca AFNetworking (https://afnetworking.com/) para extrair as duas URLs.It uses the AFNetworking library (https://afnetworking.com/) to extract the two URLs. No exemplo, created é um ponteiro para o objeto ONSCPSStandardResponse usado para armazenar os valores de resposta, e responseObject contém o JSON analisado.In the example, created is a pointer to the ONSCPSStandardResponse object used to store the response values, and responseObject holds the parsed JSON.

    /* 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];
                  }
            }
      }

Após analisar as URLs de resposta, você poderá abrir o OneNote usando o código a seguir.After you parse the URLs from the response, you can open OneNote by using the following code. Use oneNoteClientUrl o para abrir o cliente do OneNote oneNoteWebURL instalado ou para abrir o OneNote na Web.Use oneNoteClientUrl to open the installed OneNote client or oneNoteWebURL to open OneNote on the web.

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

Exemplo do AndroidAndroid example

Primeiro, verifique se há o código de status de sucesso. Em seguida, analise o JSON.First, check for the success status code, and then parse the JSON. O exemplo pressupõe que uma solicitação POST tenha sido enviada. Portanto, verifica se há um código de status 201 Created.The example assumes a POST request was sent, so it checks for a 201 Created status code. Se você tiver feito uma solicitação GET, verifique se há um código de status 200 em vez disso.If you made a GET request, check for a 200 status code instead.

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

    /* Get the response if the new page was created successfully. */
    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. */
        /* 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) {

            /* Retrieve the two URLs from the links property. */
            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;
}

Usando as propriedades de resposta, seu aplicativo pode abrir o OneNote na Web, conforme mostrado no exemplo a seguir.Using the response properties, your app can open OneNote on the web, as shown in the following example.

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

Ou o aplicativo pode abrir o cliente do OneNote em um dispositivo Android.Or your app can open the OneNote client on an Android device. Ao usar a propriedade oneNoteClientUrl, você deve colocar as cadeias de caracteres de GUID entre chaves { } antes de iniciar a Intenção.When using the oneNoteClientUrl property, you must surround the GUID strings with braces { } before starting the Intent. O exemplo a seguir mostra como fazer isso.The following example shows how to do that.

if (response.getResponseCode() == 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);
}

Confira tambémSee also