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 the domain name, ID, 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
- Log in to the DataArts Studio console.
- Click DataArts DataService.
- In the navigation pane, choose DataArts DataService Exclusive > SDKs.
- On the SDKs page, download the SDK package.
- Verify integrity of the SDK package. In Windows, open the CLI and run the following command to generate the SHA-256 value of the downloaded SDK package. In the command, D:\java-sdk.zip is an example local path and name of the SDK package. Replace it with the actual value.
certutil -hashfile D:\java-sdk.zip SHA256
The following is an example command output:
SHA-256 hash value of D:\java-sdk.zip a7c0195ebf297f29ab0065da16d7e84f14911de177e6e0c8dbadf3464d12b75f CertUtil: -hashfile command executed.
Compare the SHA-256 value of the downloaded SDK package with that provided in the following table. If they are the same, no tampering or packet loss occurred during the package download.
Language
SHA-256 Value of the SDK Package
Java
a7c0195ebf297f29ab0065da16d7e84f14911de177e6e0c8dbadf3464d12b75f
Go
caf22350181a4ecd49dc0d3f56097b10c1794792adae407140950be4ed9b6771
Python
c80b9ef282fc88d3fb16db4cb9d7525d3db71f7989782ed0b636920ea2fadb93
C#
b0e69ef60a561c54c1b86c3447ca855088a1fa2a672fbfba618aaf56b2841e8a
JavaScript
c64e595651de079766e446ce2c3262013256f81683bb9434bee27bed3a4caf01
PHP
e2eba2cae72aea794edb4057ed8eb7cb82f0dbaccabf9c5539694a7a7a9f3c89
C++
c173f59d816aba53f47750cf5ffdc65cc345b1613974b3d2a545ace48787f577
C
e4f22beb7b132fe6e57c9de79f596c3ff830228cd7221b02ca96198e501c642c
Android
d6c3032801ac88cf8cbc51f64d42457174447c8d159f34a187c036913b31ea2b
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.
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
- 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 5 Creating a project
- Import the .jar files in the API Gateway Java SDK.
- Choose java-sdk-demo, right-click, and choose Build Path > Add External Archives from the shortcut menu.
Figure 6 Importing the .jar files
- Select all .jar files in the \libs directory.
Figure 7 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 8 Creating a package
- Enter com.apig.sdk.demo for Name.
Figure 9 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 10 Creating a class
- Enter Main for Name and select public static void main(String[] args).
Figure 11 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 12 Directory structure of the new project
Before using Main.java, enter the required code according to API Calling Example.
API Calling Example
- This section demonstrates how to access a published API.
- You need to create and release an API on the DataArts DataService management console. For details about how to create and publish APIs, see DataArts Studio 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:
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: 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. For the domain name, use your own independent domain name bound to the group to which the API belongs. Use the sample code in http://{apig-endpoint}/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.
- 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://{apig-endpoint}/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; }
- Sign the request, add header x-Authorization, access the API, and print the result.
The sample code is as follows:
CloseableHttpClient client = null; try { HttpRequestBase signedRequest = Client.sign(request); Header[] authorization = signedRequest.getHeaders("Authorization"); signedRequest.addHeader("x-Authorization",authorization[0].getValue()); 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 13 Running the project test code
- On the Console tab page, view the running result.
Figure 14 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.