Updated on 2024-01-26 GMT+08:00

Android

Scenarios

To use Android to call an API through App authentication, obtain the Android SDK, create a project, and then call the API by referring to the API calling example.

Prerequisites

  • You have obtained API calling information. For details, see Preparations.
  • You have installed the Android development environment. For details, see Preparations.

Obtaining the SDK

Old version: Log in to the ROMA Connect console, choose API Connect > API Calling > SDKs, and download the SDK.

New version: Log in to the ROMA Connect console, choose API Connect > Credentials > SDKs, and download the SDK.

The following shows the directory structure after the decompression.

Name

Description

app\

Android project code

gradle\

Gradle files

build.gradle

Gradle configuration files

gradle.properties

settings.gradle

gradlew

Gradle Wrapper scripts

gradlew.bat

Opening the Sample Project

  1. Start Android Studio and choose File > Open.

    Select the directory where the SDK is decompressed.

  2. View the directory structure of the project shown in the following figure.
    Figure 1 Project directory structure

API Calling Example

  1. Add required JAR files to the app/libs directory of the Android project. The following JAR files must be included:
    • java-sdk-core-x.x.x.jar
    • joda-time-2.10.jar
  2. Add dependencies of the okhttp library to the build.gradle file.
    Add implementation 'com.squareup.okhttp3:okhttp:3.14.2' in the dependencies field of the build.gradle file.
    dependencies {    
        ...
        ...
        implementation 'com.squareup.okhttp3:okhttp:3.14.3'
    }
  3. Create a request, enter the key and secret of the authorized credential, and specify the method name, request URL, and body. For details, see Obtaining API Calling Information.
    Request request = new Request();
    try {
    // Directly writing AK/SK in code is risky. For security, encrypt your AK/SK and store them in the configuration file or environment variables. 
    // In this example, the AK/SK are stored in environment variables for identity authentication. Before running this example, set environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK. 
    	request.setKey(System.getenv("HUAWEICLOUD_SDK_AK"));
    	request.setSecrect(System.getenv("HUAWEICLOUD_SDK_SK"));
    	request.setMethod("POST");
    	request.setUrl("https://c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/app1");
    	request.addQueryStringParam("name", "value");
    	request.addHeader("Content-Type", "text/plain");
    	request.setBody("demo");
    } catch (Exception e) {
    	e.printStackTrace();
    	return;
    }
  4. Sign the request to generate an okhttp3.Request object for API access.
    okhttp3.Request signedRequest = Client.signOkhttp(request);
    OkHttpClient client = new OkHttpClient.Builder().build();
    Response response = client.newCall(signedRequest).execute();