Help Center> > Developer Guide > Calling APIs Through App Authentication >Java

Java

Scenarios

To use Java to call an API through App authentication, obtain the Java SDK, create a new project or import an existing project, and then call the API by referring to the API calling example.

This section uses Eclipse 4.5.2 as an example.

Figure 1 API calling process

Prerequisites

  • You have obtained the domain name, request URL, and request method of the API to be called, and the AppKey and AppSecret of the app for calling the API. For more information, see Preparation.
  • You have installed Eclipse 3.6.0 or a later version. If not, download Eclipse from the official Eclipse website and install it.
  • You have installed Java Development Kit (JDK) 1.8.111 or a later version. If not, download JDK from the official Oracle website and install it.

Obtaining the SDK

Download ApiGateway-java-sdk.zip. The following table shows the files decompressed from the package.

Name

Description

libs\

SDK dependencies

libs\java-sdk-core-x.x.x.jar

SDK package

src\com\apig\sdk\demo\Main.java

Sample code for signing requests

src\com\apig\sdk\demo\OkHttpDemo.java

src\com\apig\sdk\demo\LargeFileUploadDemo.java

.classpath

Java project configuration files

.project

To build a project with Maven, download the java-sdk-core-x.x.x.jar file in the SDK from https://mirrors.huaweicloud.com/repository/maven/huaweicloudsdk/.

The following are the Maven configuration items for adding the java-sdk-core dependency:

<dependency>
    <groupId>com.huawei.apigateway</groupId>
    <artifactId>java-sdk-core</artifactId>
    <version>3.0.10</version>
</dependency>

Importing a Project

  1. Open Eclipse and choose File > Import.

    The Import dialog box is displayed.

  2. Choose General > Existing Projects into Workspace and click Next.

    The Import Projects dialog box is displayed.

    Figure 2 Importing a project

  3. Click Browse and select the directory where the SDK is decompressed.

    Figure 3 Selecting the demo project

  4. Click Finish.

    The following figure shows the directory structure of the project.

    Figure 4 Directory structure of the imported project

    Modify the parameters in sample code Main.java as required. For details about the sample code, see API Calling Example.

Creating a Project

  1. Open Eclipse and choose File > New > Java Project.

    The New Java Project dialog box is displayed.

  2. Enter a project name, for example, java-sdk-demo, retain the default settings for other parameters, and click Finish.

    Figure 5 Creating a project

  3. Import the .jar files in the API Gateway Java SDK.

    1. Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
      Figure 6 Importing the .jar files
    2. Select all .jar files in the \libs directory.
      Figure 7 Selecting all .jar files

  4. Create a package and Main file.

    1. Choose src, right-click, and choose New > Package from the shortcut menu.
      Figure 8 Creating a package
    2. Enter com.apig.sdk.demo for Name.
      Figure 9 Setting a package name
    3. Click Finish.

      The package is created.

    4. Choose com.apig.sdk.demo, right-click, and choose New > Class from the shortcut menu.
      Figure 10 Creating a class
    5. Enter Main for Name and select public static void main(String[] args).
      Figure 11 Configuring the class
    6. Click Finish.

      The Main file is created.

  5. View the directory structure of the project.

    Figure 12 Directory structure of the new project

    Before using Main.java, enter the required code according to API Calling Example.

API Calling Example

NOTE:
  • This section demonstrates how to access a published API.
  • Before accessing an API, you must create and publish the API on the API Gateway console. You can specify the Mock backend for the API. For details about how to create and publish an API, see the User Guide.
  • The backend of this API is a fake HTTP service, which returns response code 200 and message body Congratulations, sdk demo is running.
  1. Add the following references to Main.java:

    import java.io.IOException;
    import javax.net.ssl.SSLContext;
    
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContexts;
    import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
    import org.apache.http.impl.client.CloseableHttpClient; 
    import org.apache.http.impl.client.HttpClients; 
    import org.apache.http.util.EntityUtils; 
    
    import com.cloud.apigateway.sdk.utils.Client; 
    import com.cloud.apigateway.sdk.utils.Request;

  2. Construct a request by configuring the following parameters:

    • AppKey: Obtain it by referring to Preparation. The sample code uses 4f5f626b-073f-402f-a1e0-e52171c6100c.
    • AppSecret: Obtain it by referring to Preparation. Set this parameter based on the site requirements. The example code uses ****** as an example.
    • Method: Specify a request method. The sample code uses POST.
    • url: Request URL of the API, excluding the QueryString and fragment parts. Use your own domain name bound to the group to which the API belongs or the domain name issued by the marketplace when publishing the API on the marketplace. The sample code uses http://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/java-sdk.
    • queryString: Specify query parameters to be carried in the URL. Characters (0-9a-zA-Z./;[]\-=~#%^&_+:") are allowed. The sample code uses name=value.
    • Header: Request header. Set a request header as required. It cannot contain underscores (_). The sample code uses Content-Type:text/plain. If you are going to publish the API in a non-RELEASE environment, specify an environment name. The sample code uses x-stage:publish_env_name.
    • body: Specify the request body. The sample code uses demo.

    The sample code is as follows:

            Request request = new Request();
            try
            {
                request.setKey("4f5f626b-073f-402f-a1e0-e52171c6100c"); //Obtain the value when creating an app.
                request.setSecret("*****"); //Obtained when an app is created.
                request.setMethod("POST");
                request.setUrl("http://c967a237-cd6c-470e-906f-a8655461897e.apigw.cn-north-1.huaweicloud.com/java-sdk");
                 //Obtain the URL when creating an API group.
                request.addQueryStringParam("name", "value");
                request.addHeader("Content-Type", "text/plain");
                //request.addHeader("x-stage", "publish_env_name"); //Specify an environment name before publishing the API in a non-RELEASE environment.
                request.setBody("demo");
            } catch (Exception e)
            {
                e.printStackTrace();
                return;
            }

  3. Sign the request, access the API, and print the result.

    The sample code is as follows:
            CloseableHttpClient client = null;
            try
            {
                HttpRequestBase signedRequest = Client.sign(request);
    
                client = HttpClients.custom().build();
                HttpResponse response = client.execute(signedRequest);
                System.out.println(response.getStatusLine().toString());
                Header[] resHeaders = response.getAllHeaders();
                for (Header h : resHeaders)
                {
                    System.out.println(h.getName() + ":" + h.getValue());
                }
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null)
                {
                    System.out.println(System.getProperty("line.separator") + EntityUtils.toString(resEntity, "UTF-8"));
                }
    
            } catch (Exception e)
            {
                e.printStackTrace();
            } finally
            {
                try
                {
                    if (client != null)
                    {
                        client.close();
                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }

  4. Choose Main.java, right-click, and choose Run As > Java Application to run the project test code.

    Figure 13 Running the project test code

  5. On the Console tab page, view the running result.

    Figure 14 Response displayed if the calling is successful