Skip to content

Protocol Methods

Weidong Xu edited this page Nov 25, 2021 · 2 revisions

Java Protocol Methods

Our protocols methods provide simple, reliable connections to APIs for previews and advanced usage.

Here's how to get started

pom.xml

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-core</artifactId>
  <version>1.23.0</version>
</dependency>

Application.java

ExampleClient client = new ExampleClientBuilder()
    .endpoint("https://example.org/")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Response<BinaryData> response = client.getHelloWithResponse(/*RequestOptions*/null);

if (response.getStatusCode() != 200) {
    System.out.println("Failed with message " + response.getValue().toString());
} else {
    System.out.println("Succeeded with message " + response.getValue().toString());
}

Code Snippets

Code snippets for how to use our protocol methods:

  1. Sample using JSON-P
  2. Sample using Jackson

What is a protocol method

Our protocol methods provide simple, reliable connection to raw HTTP for previews and advanced usage. Calls through this method fully harness the power of azure-core and azure-identity. We provide both synchronous and asynchronous protocol methods.

The basic structure of calls with protocol methods is:

  1. Initialize your client
  2. Send the request
  3. Handle the response

We will go into each step in the following sections

1. Initialize Your Client

Protocol methods are accessed from the same client where high level methods are. The client can be created from a builder named {ServiceName}Builder. There is one builder in one library that can be used to create all the low level clients.

Most clients require authenticating through their credential parameter. Depending on what authentication support your library is using, you can either authenticate-with-aad or authenticate with an AzureKeyCredential.

Additionally, most of our clients accept an endpoint parameter at initialization, usually a link to your own resource.

Authenticating with AAD

Depending on your library, our clients support authenticating with an Azure Active Directory (AAD) token credential. We always recommend using a credential type obtained from the azure-identity library for AAD authentication. For this example, we use the most common DefaultAzureCredential.

As an installation note, the azure-identity library is not a dependency of this library. Please add com.azure:azure-identity to your pom.xml before using AAD authentication:

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-identity</artifactId>
  <version>1.4.1</version>
</dependency>

The following code snippet shows you how to authenticate with a DefaultAzureCredential.

ExampleClient client = new ExampleClientBuilder()
    .endpoint("https://example.org/")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Authenticating with AzureKeyCredential

Some libraries support authenticating with an AzureKeyCredential. The following code snippet shows you how to authenticate with an AzureKeyCredential

HttpPipelinePolicy authPolicy = new AzureKeyCredentialPolicy(
    "key-name",
    new AzureKeyCredential("key-value"));

ExampleClient client = new ExampleClientBuilder()
    .endpoint("https://example.org/")
    .credential(new AzureKeyCredential("key"))
    .build();

2. Send a request

All client methods in the low level client will list all the required path, query, header, body parameters, and a RequestOptions parameter in the parameter list for the specific service method call. The RequestOptions parameter allows users to manipulate all aspects of the requests, before it is ultimately sent to the appropriate Azure endpoint.

The return type will be of Response<BinaryData> for sync APIs and Mono<Response<BinaryData>> for async APIs.

Response<BinaryData> methodCallWithResponse(String param1, String param2, BinaryData body, RequestOptions options);
Mono<Response<BinaryData>> methodCallWithResponse(String param1, String param2, BinaryData body, RequestOptions options);

RequestOptions

The RequestOptions object allows customizing the HTTP request before the it's sent out. Most aspects of the request can be customized here, including URL, HTTP method, path parameters, query parameters, header parameters, and the request context.

When an API method from the Swagger spec is called, the URL, HTTP method, and the required parameters will be populated during the method call. Only the optional parameters should be specified as needed in RequestOptions, before the request is handed off to the HttpPipeline to be sent.

package com.azure.core.http.rest;

public class RequestOptions {
    public RequestOptions() { }

    public RequestOptions addQueryParam(String parameterName, String value);
    public RequestOptions addHeader(String header, String value);
    public RequestOptions setHeader(String header, String value);
    public RequestOptions addRequestCallback(Consumer<HttpRequest> requestCallback);
    public RequestOptions setBody(BinaryData requestBody);
    public RequestOptions setContext(Context context);
}

Request body

The request body will be provided in type BinaryData. Users can choose the to use byte[], String or Flux<ByteBuffer> to populate the request content.

Optional query & header parameters

The optional query & header parameters can be specified on the RequestOptions.

RequestOptions options = new RequestOptions()
    .addQueryParam("skipEncoding", "true")
    .addHeader("x-ms-header", "foo");
client.invokeWithResponse(options); // Response<>

Request URL & HTTP method

The request URL and HTTP method are settable on RequestOptions as a request callback:

RequestOptions options = new RequestOptions()
    .addRequestCallback(request -> {
        request.setHttpMethod(HttpMethod.POST);
    })
client.invokeWithResponse(options); // Response<>

Users can also call the "catch-all" invokeWithResponse() method on the client to send an arbitrary request with the current http pipeline:

public Response<BinaryData> invokeWithResponse(String url, HttpMethod httpMethod, BinaryData body, RequestOptions options);

3. Handle the Response

BinaryData

The protocol methods will return type Response<BinaryData> where BinaryData stores the response body. You can then convert the response body to the type you like.

Headers

The headers will be accessible as from Response<> type.

Examples

Sample using JSON-P

This is an example of using JSON-P for constructing a request and parsing a response:

TextAnalyticsClient client = new TextAnalyticsClientBuilder()
     .credential(new AzureKeyCredential("{ApiKey}"))
     .endpoint("{Endpoint}")
     .httpClient(HttpClient.createDefault())
     .buildClient();

JsonObject document = Json.createObjectBuilder()
    .add("id", "0")
    .add("text", "Old Faithful is a geyser at Yellowstone Park.")
    .build();

JsonObject batchInput = Json.createObjectBuilder()
    .add("documents", Json.createArrayBuilder().add(document).build())
    .build();

String response = client.entitesLinkingWithResponse(BinaryData.fromString(requestBody.toString()), null)
    .getValue().toString();

JsonReader jsonReader = Json.createReader(new StringReader(response));
JsonObject result = jsonReader.readObject();

result.getJsonArray("entities").forEach(linkedEntity -> {
    JsonObject entity = linkedEntity.asJsonObject();
    System.out.println("Linked Entities:");
    System.out.printf("Name: %s, data source: %s, URL: %s, Bing Entity Search API ID: %s.%n",
            entity.getString("name"), entity.getString("dataSource"), entity.getString("url"), entity.getString("bingId"));
    entity.getJsonArray("matches").forEach(entityMatch -> {
        JsonObject match = entity.asJsonObject();
        System.out.printf("Matched entity: %s, confidence score: %f.%n",
                match.getString("text"), match.getJsonNumber("confidenceScore").doubleValue());
    });
});
Clone this wiki locally