Route
Confirm Endpoint
When confirming the Endpoint configured when you use the SDK, you can first read the section on API Access Domain Name in the Developer Guide to understand the Endpoint concept. Baidu AI Cloud enables multi-region support currently, please see the description of Region Selection Introduction.
The information corresponding to the currently supported regions is:
Access region | Corresponding Endpoint |
---|---|
Beijing | bcc.bj.baidubce.com |
Guangzhou | bcc.gz.baidubce.com |
Suzhou | bcc.su.baidubce.com |
Hong Kong | bcc.hkg.baidubce.com |
Wuhan | bcc.fwh.baidubce.com |
Baoding | bcc.bd.baidubce.com |
Get the Key
To use Baidu AI Cloud Route, you need to have a valid AK (Access Key ID) and SK (Secret Access Key) for signature authentication. AK/SK is assigned to users by the system and is a string to identify users and verify signatures for accessing Route. You can obtain and understand your AK/SK information through the following steps:
Register Baidu AI Cloud Account
[Create AK/SK](https://login.bce.baidu.com/? account=&redirect=https://console.bce.baidu.com/iam/? _=1513940574695#/iam/accesslist)
Create RouteClient
Being the client of the Route service, RouteClient provides a series of methods for developers to interact with the Route service.
Create RouteClient using AK/SK To access Route through AK/SK, users can see the following code to create a RouteClient:
public class Sample {
public static void main(String[] args) {
String ACCESS_KEY_ID = <your-access-key-id>; // User's Access Key ID
String SECRET_ACCESS_KEY = <your-secret-access-key>; // User's Secret Key
//Initialize one RouteClient.
BceClientConfiguration config = new BceClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
RouteClient client = new RouteClient(config);
}
}
In the above code, ACCESS_KEY_ID
corresponds to the "Access Key ID" in the console, and SECRET_ACCESS_KEY
corresponds to the "Access Key Secret" in the console. For how to obtain it, please see [ACCESSKEY Management] in the Operation Guide (https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/).
The above method uses the default domain name as the service address of the Route. If the user needs to specify the domain name himself, he can specify it by passing in the ENDPOINT parameter.
String ACCESS_KEY_ID = <your-access-key-id>; // User's Access Key ID
String SECRET_ACCESS_KEY = <your-secret-access-key>; // User's Secret Key
String ENDPOINT = <domain-name>; //User-specified domain name
BceClientConfiguration config = new BceClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID,SECRET_ACCESS_KEY));
config.setEndpoint(ENDPOINT);
RouteClient client = new RouteClient(config);
Note: The
ENDPOINT
parameter can only be defined with the specified domain name of the areas included. If not specified, it defaults to the Beijing area
Use STS to Create RouteClient
Apply for STS Token
Route can implement temporary authorized access by a third party through the STS mechanism. STS (Security Token Service) is a temporary authorization service provided by Baidu AI Cloud. With STS, you can issue a third-party user with a custom time-based and privileged access credential. The third-party user can use the access credential to directly call API or SDK of Baidu AI Cloud to access its resources.
To access to Route via STS, you need to apply for an authentication string via client of STS, for the application method, please see Introduction to use of Baidu AI Cloud STS.
Use STS Token to Create RouteClient
After applying for STS, you can configure the STS token into RouteClient. Users can create RouteClient referring to the following codes:
public class StsExample {
private static final String STS_ENDPOINT = "http://sts.bj.baidubce.com";
private static final String ACCESS_KEY_ID = "your accesskey id";
private static final String SECRET_ACCESS_KEY = "your secret accesskey";
public static void main(String[] args) {
BceCredentials credentials = new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
StsClient client = new StsClient(
new BceClientConfiguration().withEndpoint(STS_ENDPOINT).withCredentials(credentials)
);
GetSessionTokenResponse response = client.getSessionToken(new GetSessionTokenRequest());
// or simply call:
// GetSessionTokenResponse response = client.getSessionToken();
// or you can specify limited permissions with ACL:
// GetSessionTokenResponse response = client.getSessionToken(new GetSessionTokenRequest().withAcl("blabla"));
// build DefaultBceSessionCredentials object from response:
BceCredentials routestsCredentials = new DefaultBceSessionCredentials(
response.getAccessKeyId(),
response.getSecretAccessKey(),
response.getSessionToken());
System.out.println("==================================");
System.out.println("GetSessionToken result:");
System.out.println(" accessKeyId: " + response.getAccessKeyId());
System.out.println(" secretAccessKey: " + response.getSecretAccessKey());
System.out.println(" securityToken: " + response.getSessionToken());
System.out.println(" expiresAt: " + response.getExpiration().toString());
System.out.println("==================================");
// build Route client
BceClientConfiguration config = new BceClientConfiguration();
config.setCredentials(routestsCredentials);
RouteClient routeClient = new RouteClient(config);
}
}
Note: When a client is configured using STS, the endpoint must be configured to http://sts.bj.baidubce.com regardless of the endpoint corresponding to the Route service.
Configure HTTPS to Access Route
Route supports HTTPS, and you can access to Route service with HTTP in Route Java SDK with the following 2 methods:
- Indicate https in endpoint
String endpoint = "https://bcc.bj.baidubce.com";
String ak = "ak";
String sk = "sk";
BceClientConfiguration config = new BceClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ak, sk));
RouteClient client = new RouteClient(config);
- Set the https protocol by calling the setProtocol method:
String endpoint = "bcc.bj.baidubce.com"; // endpoint does not contain protocol.
String ak = "ak";
String sk = "sk";
BceClientConfiguration config = new BClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ak, sk));
config.setEndpoint(ENDPOINT);
config.setProtocol(Protocol.HTTPS); // If protocol is not indicated, http is used.
RouteClient client = new RouteClient(config);
Note: If protocol is indicated in endpoint, the entry in endpoint takes effect, and a separate call to setProtocol () does not work.
String endpoint = "https://bcc.bj.baidubce.com";
String ak = "ak";
String sk = "sk";
BceClientConfiguration config = new BceClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ak, sk));
config.setEndpoint(ENDPOINT);
config.setProtocol(Protocol.HTTPS); // As indicated in endpoint, this is an invalid operation, as is http.
RouteClient client = new RouteClient(config);
Configure RouteClient
If you need to configure some detailed parameters of the RouteClient, introduce into the BceClientConfiguration object when the RouteClient is constructed. BceClientConfiguration is the configuration class of RouteClient service, and it can configure agent, maximum connection number and other parameters for the client.
Use Agent
The following codes enable client to use agent to access Route service:
String ACCESS_KEY_ID = <your-access-key-id>; // User's Access Key ID
String SECRET_ACCESS_KEY = <your-secret-access-key>; // User's Secret Key
String ENDPOINT = <domain-name>; //User-specified domain name
//Creation of BceClientConfiguration instance
BceClientConfiguration config = new BceClientConfiguration();
//Configure the agent as local 8080 port
config.setProxyHost("127.0.0.1");
config.setProxyPort(8080);
//Create Route client
config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID,SECRET_ACCESS_KEY));
config.setEndpoint(ENDPOINT);
RouteClient client = new RouteClient(config);
Using the code segment above, all operations of client are executed as an agent via the 8080 port of 127.0.0.1 address.
For the agent with user authentication, the following code segment can be used to configure username and password:
//Creation of BceClientConfiguration instance
BceClientConfiguration config = new BceClientConfiguration();
//Configure the agent as local 8080 port
config.setProxyHost("127.0.0.1");
config.setProxyPort(8080);
// Set username and password
config.setProxyUsername(<username>); //User name
config.setProxyPassword(<password>); //Password
Set Network Parameters
You can set the basic network parameters with BceClientConfiguration.
BceClientConfiguration config = new BceClientConfiguration();
//Set the maximum number of HTTP connections to 10.
config.setMaxConnections(10);
//Set TCP connection timeout to 5,000 milliseconds
config.setConnectionTimeout(5000);
//Set the timeout for socket data transmission to 2,000 milliseconds
config.setSocketTimeout(2000);
Parameter Description
All parameters that can be specified via BceClientConfiguration are listed as follows:
Parameter | Description |
---|---|
UserAgent | User agent, referring to the HTTP User-Agent header |
Protocol | Connection protocol type |
ProxyDomain | Windows domain name for access to NTLM authenticated proxy server |
ProxyHost | Proxy server host address |
ProxyPort | Proxy server port |
ProxyUsername | User name for proxy server authentication |
ProxyPassword | Password for proxy server authentication |
ProxyPreemptiveAuthenticationEnabled | Whether to set up user agent authentication |
ProxyWorkstation | Windows workstation name of the NTLM proxy server |
LocalAddress | Local address |
ConnectionTimeoutInMillis | Timeout for establishing a connection (unit: millisecond) |
SocketTimeoutInMillis | Timeout for transmitting data over open connections (unit: millisecond) |
MaxConnections | Maximum number of HTTP connections allowed to open |
RetryPolicy | Connection retry policy |
SocketBufferSizeInBytes | Socket buffer size |
StreamBufferSize | Stream file buffer size |
Query a Route Table
For query of a route table, the request's parameter routeTableId and vpcId cannot be simultaneously empty.
The instance code for query of a route table is as below:
public GetRouteResponse getRoute(String routeTableId, String vpcId) {
GetRouteRequest request = new GetRouteRequest();
//The parameter routeTableId and vpcId cannot be simultaneously empty.
if (Strings.isNullOrEmpty(vpcId) && Strings.isNullOrEmpty(routeTableId)) {
throw new IllegalArgumentException("routeTableId and vpcId should not be empty at the same time");
}
else if (!Strings.isNullOrEmpty(routeTableId)) {
//Set the route table id to be queried.
request.withRouteTableId(routeTableId);
}
else if (!Strings.isNullOrEmpty(vpcId)) {
//Set the id of vpc to be queried..
request.withVpcId(vpcId);
}
return getRoutes(request);
}
You can also customize and configure even more other parameters, and the request parameters are as follows:
Parameter name | Type | Required or not | Description |
---|---|---|---|
version | String | Yes | API version number |
routeTableId | String | No | At least one of the route table id and the vpcId should be selected. |
vpcId | String | No | At least one of the id of VPC and the routeTableId should be selected. |
The codes are as follows:
private GetRouteResponse getRoutes(GetRouteRequest getRouteRequest) {
//Verify whether the request parameter is null.
checkNotNull(getRouteRequest, "route request should not be null");
//Verify whether the routeTableId and vpcId are simultaneously null.
if (Strings.isNullOrEmpty(getRouteRequest.getRouteTableId())
&& Strings.isNullOrEmpty(getRouteRequest.getVpcId())) {
throw new IllegalArgumentException("routeTableId and vpcId cannot be empty at the same time");
}
//Build a request.
InternalRequest internalRequest = this.createRequest(
getRouteRequest, HttpMethodName.GET, ROUTE_PREFIX);
//Set vpcId or routeTableId parameter.
if (!Strings.isNullOrEmpty(getRouteRequest.getVpcId())) {
internalRequest.addParameter("vpcId", getRouteRequest.getVpcId());
}
else if (!Strings.isNullOrEmpty(getRouteRequest.getRouteTableId())) {
internalRequest.addParameter("routeTableId", getRouteRequest.getRouteTableId());
}
return this.invokeHttpClient(internalRequest, GetRouteResponse.class);
}
Return Parameter Description
The return GetRouteRequest parameter is as shown below:
Parameter name | Type | Description |
---|---|---|
routeTableId | String | Route table id |
vpcId | String | Id of vpc to which the route table belongs |
routeRules | RouteRule | Routing rules |
RouteRule
Parameter name | Type | Description |
---|---|---|
routeRuleId | String | Route rule id |
routeTableId | String | Route table id |
sourceAddress | String | Source network segment |
destinationAddress | String | Destination network segment |
nexthopId | String | The next hop id, when nexthopType is the local gateway type, this field can be empty. |
nexthopType | String | Route type. The Bcc type is "custom"; the VPN type is "vpn"; the NAT type is "nat"; the default type of the system is "sys". VPC automatically generate one default route rule for each subnet. This route rule id of this type is empty, and cannot be edited and deleted. |
description | String | Description |
Create Route Rule
To create route table rules, you need to pay attention to the following points:
- When "Custom" is selected for the source segment, the customized segment need to be within the existing subnet range, excluding 0.0.0.0/0;
- The target network and the current VPC cidr cannot overlap (except when the target segment or the VPC cidr is 0.0.0.0/0);
- The source segment and target segment of added route entries cannot be completely consistent with those of existing entries in the route table.
The request parameters are as follows:
Parameter name | Type | Required or not | Description |
---|---|---|---|
version | String | Yes | API version number |
clientToken | String | No | The idempotence Token is a ASCII string with the length of no more than 64 bits. |
routeTableId | String | Yes | Route table id |
sourceAddress | String | Yes | For the source segment, you can fill in all network segments 0.0.0.0/0, existing subnet segments in VPC or segments in the subnet range. |
destinationAddress | String | Yes | The target segment can be 0.0.0.0/0, or the destination address and the current VPC cidr cannot overlap (except when the destination segment or the VPC cidr is 0.0.0.0/0). |
nexthopId | String | No | Next hop id |
nexthopType | String | Yes | Route type. The Bcc type is "custom"; the VPN type is "vpn"; the NAT type is "nat". |
description | String | Yes | Description |
public CreateRouteResponse createRoute(CreateRouteRequest request) throws BceClientException {
//Verify whether the request parameter is null.
checkNotNull(request, "request should not be null.");
//Verify whether clientToken exists.
if (Strings.isNullOrEmpty(request.getClientToken())) {
request.setClientToken(this.generateClientToken());
}
//Set the parameters such as route table id, source segment, destination segment, next hop type, and description.
checkStringNotEmpty(request.getRouteTableId(), "routeTableId should not be empty");
checkStringNotEmpty(request.getSourceAddress(), "source address should not be empty");
checkStringNotEmpty(request.getDestinationAddress(), "destination address should not be empty");
checkStringNotEmpty(request.getNexthopType(), "nexthop type should not be empty");
checkStringNotEmpty(request.getDescription(), "description should not be empty");
//Build a request.
InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, ROUTE_PREFIX, ROUTE_RULE);
internalRequest.addParameter("clientToken", request.getClientToken());
fillPayload(internalRequest,request);
return invokeHttpClient(internalRequest, CreateRouteResponse.class);
}
Return parameter description
The return CreateRouteResponse parameter is as shown below:
Parameter name | Type | Description |
---|---|---|
routeRuleId | String | Route rule id |
Delete Routing Rule
The route rules can be deleted according to routeRuleId.
public void deleteRouteRule(String routeRuleId) {
deleteRouteRule(new DeleteRouteRequest().withRouteRuleId(routeRuleId));
}
You can also customize and configure even more other parameters, and the request parameters are as follows:
Parameter name | Type | Required or not | Description |
---|---|---|---|
version | String | Yes | API version number |
clientToken | String | No | The idempotence Token is a ASCII string with the length of no more than 64 bits. |
routeRuleId | String | Yes | Route rule id |
The codes are as follows:
public void deleteRouteRule(DeleteRouteRequest deleteRouteRequest) {
//Verify whether the parameter is null.
checkNotNull(deleteRouteRequest, "request should not be null.");
//Verify whether the routeruleid is null.
checkNotNull(deleteRouteRequest.getRouteRuleId(), "request routeRuleId should not be null.");
//If the user sets clientToken, this parameter is set.
if (Strings.isNullOrEmpty(deleteRouteRequest.getClientToken())) {
deleteRouteRequest.setClientToken(this.generateClientToken());
}
//Build a request.
InternalRequest internalRequest = this.createRequest(
deleteRouteRequest, HttpMethodName.DELETE, ROUTE_PREFIX, ROUTE_RULE,
deleteRouteRequest.getRouteRuleId());
internalRequest.addParameter("clientToken", deleteRouteRequest.getClientToken());
this.invokeHttpClient(internalRequest, AbstractBceResponse.class);
}