Java
Scenarios
To use Java to call an API through app authentication, obtain the Java SDK, create a 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.
Prerequisites
- You have obtained API calling information. For details, 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. JDK 17 or later is not supported.
Obtaining the SDK
Log in to the APIG console, and download the SDK on the SDKs page by referring to section "SDKs" in the API Gateway User Guide.
Then obtain the ApiGateway-java-sdk.zip package. 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 |
Importing a Project
- Open Eclipse and choose File > Import.
The Import dialog box is displayed.
- Choose General > Existing Projects into Workspace and click Next.
The Import Projects dialog box is displayed.
Figure 2 Importing a project
- Click Browse and select the directory where the SDK is decompressed.
Figure 3 Selecting the demo project
- Click Finish.
Modify the parameters in sample code Main.java as required. For details about the sample code, see API Calling Example.
Creating a Project
- Open Eclipse and choose File > New > Java Project.
The New Java Project dialog box is displayed.
- Enter a project name, for example, java-sdk-demo, retain the default settings for other parameters, and click Finish.
Figure 4 Creating a project
- Import the .jar files in the APIG Java SDK.
- Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
Figure 5 Importing the .jar files
- Select all .jar files in the \libs directory.
Figure 6 Selecting all .jar files
- Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
- Create a package and Main file.
- Choose src, right-click, and choose New > Package from the shortcut menu.
Figure 7 Creating a package
- Enter com.apig.sdk.demo for Name.
Figure 8 Setting a package name
- Click Finish.
The package is created.
- Choose com.apig.sdk.demo, right-click, and choose New > Class from the shortcut menu.
Figure 9 Creating a class
- Enter Main for Name and select public static void main(String[] args).
Figure 10 Configuring the class
- Click Finish.
The Main file is created.
- Choose src, right-click, and choose New > Package from the shortcut menu.
- View the directory structure of the project.
Figure 11 Directory structure of the new project Main
Before using Main.java, enter the required code according to the API calling example provided in this section.
API Calling Example
- You need to create an API with the Mock backend on the console, and then publish the API. For details about how to create and publish an API, see the API Gateway 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.
- Add the following references to Main.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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;
- Construct a request by configuring the following parameters:
- AppKey and AppSecret: In this example, the AK and SK stored in the environment variables are used. Specify the environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment first. The following uses Linux as an example to describe how to set the obtained AK/SK as environment variables and fill them in the sample code.
- Open the terminal and run the following command to open the environment variable configuration file:
- Set environment variables, save the file, and exit the editor.
export CLOUD_SDK_AK="Obtained AK" export CLOUD_SDK_SK="Obtained SK"
- Run the following command to apply the modification:
- 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 independent domain name. The sample code uses http://c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.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: Specify request headers. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Request request = new Request(); try { request.setKey(System.getenv("CLOUD_SDK_AK")); request.setSecret(System.getenv("CLOUD_SDK_SK")); request.setMethod("POST"); request.setUrl("http://c967a237-cd6c-470e-906f-a8655461897e.apigw.exampleRegion.com/java-sdk"); //URL 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; }
- AppKey and AppSecret: In this example, the AK and SK stored in the environment variables are used. Specify the environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment first. The following uses Linux as an example to describe how to set the obtained AK/SK as environment variables and fill them in the sample code.
- Sign the request, access the API, and print the result.
The sample code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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(); } }
- Choose Main.java, right-click, and choose Run As > Java Application to run the project test code.
Figure 12 Running the project test code
- On the Console tab page, view the running result.
Figure 13 Response displayed if the calling is successful
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot