Initialization
Confirm Endpoint
When confirming the endpoint configured when using the SDK, you can first read the relevant content in the developer guide regarding [BOS endpoint](BOS/Developer Guide/Basic concepts.md#Access a domain name) section in the API documentation to understand Endpoint concepts. Baidu AI Cloud currently supports multiple regions. Please refer to[Region Selection Guide](Reference/Region Selection Instructions/Region.md).
Currently, multiple regions are supported, and the corresponding information is as follows:
| Region | Access endpoint | Supported protocols |
|---|---|---|
| Beijing | bj.bcebos.com | HTTP,HTTPS |
| Baoding | bd.bcebos.com | HTTP,HTTPS |
| Suzhou | su.bcebos.com | HTTP,HTTPS |
| Guangzhou | gz.bcebos.com | HTTP,HTTPS |
| Chengdu | cd.bcebos.com | HTTP,HTTPS |
| Hong Kong | hkg.bcebos.com | HTTP,HTTPS |
| Wuhan | fwh.bcebos.com | HTTP,HTTPS |
| Shanghai Zone of Financial Cloud | fsh.bcebos.com | HTTP,HTTPS |
Retrieve access key
To use Baidu AI Cloud BOS, you need a valid AK (Access Key ID) and SK (Secret Access Key) for signature certification. AK/SK are system-assigned strings used to identify users and perform signature certification for BOS. Your AK/SK information can be obtained and understood through the following steps:
Register a Baidu AI Cloud account
Create a BosClient
BosClient functions as a client for BOS services, giving developers various methods to interact with these services.
Create a BosClient with AK/SK
Users can refer to the following code to create a BosClient to access BOS with AK/SK:
1public class Sample {
2public static void main(String[] args) {
3 String ACCESS_KEY_ID =<your-access-key-id>; // User’s Access Key ID
4 String SECRET_ACCESS_KEY =<your-secret-access-key>; // User’s Secret Access Key
5
6 // Initialize a BOSClient
7 BosClientConfiguration config = new BosClientConfiguration();
8 config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
9 BosClient client = new BosClient(config);
10 }
11}
In the code above, ACCESS_KEY_ID corresponds to “Access Key ID” in the console. SECRET_ACCESS_KEY corresponds to “Access Key Secret” in the console. For the method to retrieve them, refer to the Guide - [Manage ACCESSKEY](Reference/Retrieve AK and SK/How to Obtain AKSK.md).
You can specify the official BOS domain names of different regions by passing in the ENDPOINT parameter. If not specified, the default is the Beijing region http://bj.bcebos.com.
1String ACCESS_KEY_ID =<your-access-key-id>; // User’s Access Key ID
2 String SECRET_ACCESS_KEY =<your-secret-access-key>; // User’s Secret Access Key
3 String ENDPOINT = <domain-name>; // User-defined domain name
4BosClientConfiguration config = new BosClientConfiguration();
5config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID,SECRET_ACCESS_KEY));
6config.setEndpoint(ENDPOINT);
7BosClient client = new BosClient(config);
Note: If you need to access using a custom domain name, in addition to modifying the
ENDPOINTparameter, you also need to enable the custom domain name switch. For details, see the following Configure Custom Domain Name to Access BOS.
Create a BosClient with STS
Request STS Token
BOS allows temporary third-party access authorization using the STS mechanism. STS (Security Token Service) is a temporary authorization tool provided by Baidu AI Cloud, enabling you to issue access credentials with customized validity periods and permissions for third-party users. These users can use the credentials to call Baidu AI Cloud APIs or SDKs directly to access cloud resources.
To access BOS via STS, users must first request a certification string through the STS client. For instructions on obtaining STS credentials, refer to [Baidu AI Cloud STS Usage Guide](BOS/API Reference/Access control.md).
Create BOSClient with STS token
After requesting the STS token, configure it in the BosClient. The following codes demonstrate how to create a BosClient:
1public class StsExample {
2 private static final String STS_ENDPOINT = "http://sts.bj.baidubce.com";
3 private static final String ENDPOINT = "bj.bcebos.com";
4 private static final String ACCESS_KEY_ID = "your accesskey id";
5 private static final String SECRET_ACCESS_KEY = "your secret accesskey";
6 public static void main(String[] args) {
7 BceCredentials credentials = new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
8 StsClient client = new StsClient(
9 new BceClientConfiguration().withEndpoint(STS_ENDPOINT).withCredentials(credentials)
10 );
11 GetSessionTokenResponse response = client.getSessionToken(new GetSessionTokenRequest());
12 // or simply call:
13 // GetSessionTokenResponse response = client.getSessionToken();
14 // or you can specify limited permissions with ACL:
15 // GetSessionTokenResponse response = client.getSessionToken(new GetSessionTokenRequest().withAcl("blabla"));
16 // build DefaultBceSessionCredentials object from response:
17 BceCredentials bosstsCredentials = new DefaultBceSessionCredentials(
18 response.getAccessKeyId(),
19 response.getSecretAccessKey(),
20 response.getSessionToken());
21 System.out.println("==================================");
22 System.out.println("GetSessionToken result:");
23 System.out.println(" accessKeyId: " + response.getAccessKeyId());
24 System.out.println(" secretAccessKey: " + response.getSecretAccessKey());
25 System.out.println(" securityToken: " + response.getSessionToken());
26 System.out.println(" expiresAt: " + response.getExpiration().toString());
27 System.out.println("==================================");
28 // build bos client
29 BosClientConfiguration config = new BosClientConfiguration();
30 config.setCredentials(bosstsCredentials);
31 config.setEndpoint(ENDPOINT);
32 BosClient bosClient = new BosClient(config);
33 }
34}
Note: Currently, when configuring a client using STS, regardless of the region where the corresponding bucket is located, the endpoint must be configured as
http://sts.bj.baidubce.com, However, when creating a BosClient, you still need to use the BOS endpoint, such asbj.bcebos.com,su.bcebos.com, etc.
Configure custom domain name to access BOS
Use a custom domain name
If you want to use a custom domain name as the endpoint to access BOS, after binding the custom domain name to a BOS bucket in the console, configure the endpoint as the custom domain name and turn on the CnameEnabled switch, such as cdn-test.cdn.bcebos.com. The configuration code is as follows:
1String ACCESS_KEY_ID =<your-access-key-id>; // User’s Access Key ID
2 String SECRET_ACCESS_KEY =<your-secret-access-key>; // User’s Secret Access Key
3 String ENDPOINT = "https://cdn-test.cdn.bcebos.com"; //User-defined domain name
4 BosClientConfiguration config = new BosClientConfiguration();
5 config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID,SECRET_ACCESS_KEY));
6 config.setEndpoint(ENDPOINT);
7 config.setCnameEnabled(true);
8 BosClient client = new BosClient(config);
Configure HTTPS access to BOS
BOS supports HTTPS transport protocol. You can use HTTPS to access the BOS service in the BOS Java SDK in the following two ways:
-
Specify HTTPS in the endpoint:
Java1String endpoint = "https://bj.bcebos.com"; 2String ak = "ak"; 3String sk = "sk"; 4BosClientConfiguration config = new BosClientConfiguration(); 5config.setCredentials(new DefaultBceCredentials(ak, sk)); 6config.setEndpoint(endpoint); 7BosClient client = new BosClient(config); -
Configure HTTPS by calling setProtocol:
Java1String endpoint = "bj.bcebos.com"; // endpoint without protocol 2String ak = "ak"; 3String sk = "sk"; 4BosClientConfiguration config = new BosClientConfiguration(); 5config.setCredentials(new DefaultBceCredentials(ak, sk)); 6config.setEndpoint(endpoint); 7 config.setProtocol(Protocol.HTTPS); // Defaults to HTTP if unspecified 8BosClient client = new BosClient(config);Plain Text1> **Note:** If the endpoint already includes a protocol, the protocol in the endpoint will take precedence, and the setProtocol() method will be ignored.Java1String endpoint = "http://bj.bcebos.com"; 2String ak = "ak"; 3String sk = "sk"; 4BosClientConfiguration config = new BosClientConfiguration(); 5config.setCredentials(new DefaultBceCredentials(ak, sk)); 6config.setEndpoint(endpoint); 7 config.setProtocol(Protocol.HTTPS); // Invalid operation if specified in endpoint, applicable to HTTP cases 8BosClient client = new BosClient(config);
Configure BosClient
If detailed configurations are required for the BosClient, the user can pass a BosClientConfiguration object during its construction. The BosClientConfiguration class is designed to set parameters like proxies and the maximum number of connections for the client.
Use a proxy
The following code snippet enables the client to access BOS service using a proxy:
1String ACCESS_KEY_ID =<your-access-key-id>; // User’s Access Key ID
2 String SECRET_ACCESS_KEY =<your-secret-access-key>; // User’s Secret Access Key
3 String ENDPOINT = <domain-name>; // User-defined domain name
4 // Create BosClientConfiguration instance
5BosClientConfiguration config = new BosClientConfiguration();
6 // Configure proxy to local port 8080
7config.setProxyHost("127.0.0.1");
8config.setProxyPort(8080);
9 // Create BOS client
10config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID,SECRET_ACCESS_KEY));
11config.setEndpoint(ENDPOINT);
12BosClient client = new BosClient(config);
All client requests will then be routed through the proxy at 127.0.0.1:8080.
For verified proxies, configure credentials:
1// Create BosClientConfiguration instance
2BosClientConfiguration config = new BosClientConfiguration();
3
4 // Configure proxy to local port 8080
5config.setProxyHost("127.0.0.1");
6config.setProxyPort(8080);
7
8 // Set username and password
9 config.setProxyUsername(<username>); // Username
10 config.setProxyPassword(<password>); // Password
Set network parameters
Users may set the basic network parameters with BosClientConfiguration:
1BosClientConfiguration config = new BosClientConfiguration();
2
3 // Set maximum number of HTTP connections to 10
4config.setMaxConnections(10);
5
6 // Set TCP connection timeout to 5,000 milliseconds
7config.setConnectionTimeoutInMillis(5000);
8
9 // Set timeout for Socket data transmission to 2,000 milliseconds
10config.setSocketTimeoutInMillis(2000);
Set access to domain name style
After version 0.10.227, the SDK will enable bucket virtual hosting by default automatically. You can enable the use of PathStyle-style endpoints through the following configuration:
1BosClientConfiguration config = new BosClientConfiguration();
2 // Enable PathStyle
3config.setPathStyleAccessEnable(true);
Note: Under some non-conventional BOS domain names, the default bucket virtual hosting style may have incompatibility issues, such as DNS resolution failures. This can be resolved by enabling PathStyle. It is recommended to use the default style in other scenarios.
Set redirection
From version 0.10.330 onward, the SDK disables automatic redirection by default for security reasons. Users can enable redirection and set related parameters using the following configurations:
1BosClientConfiguration config = new BosClientConfiguration();
2 // Enable automatic redirection
3config.setRedirectsEnabled(true);
4 // Set the maximum number of automatic redirections
5config.setMaxRedirects(10);
Set synchronous PUT
For PUT operations, CloseableHttpAsyncClient is used by default, which might prevent the user process from exiting after execution. You can configure the BosClient through BosClientConfiguration to set all BOS requests to run synchronously:
1BosClientConfiguration config = new BosClientConfiguration();
2 // Set PUT operation to synchronous mode, asynchronous by default
3config.setEnableHttpAsyncPut(false);
Parameter description
The following parameters can be configured via BosClientConfiguration:
| Parameters | Description |
|---|---|
| CnameEnabled | Use CNAME to access BOS resources |
| ConnectionTimeoutInMillis | Timeout for establishing TCP connections (unit: ms) |
| Credentials | Client credentials for signing HTTP requests with BCE |
| EnableHttpAsyncPut | Asynchronous put |
| Endpoint | Access a domain name |
| LocalAddress | Local address |
| MaxConnections | Maximum allowable HTTP connections |
| Protocol | Connection protocol type |
| ProxyDomain | Windows domain for NTLM-verified proxy |
| ProxyHost | Proxy server host address |
| ProxyPassword | Proxy verification password |
| ProxyPort | Proxy server port |
| ProxyPreemptiveAuthenticationEnabled | Enable user agent verification or not |
| ProxyUsername | Proxy verification username |
| ProxyWorkstation | NTLM proxy workstation name |
| Region | Region |
| RetryPolicy | Retry policy for connections |
| SocketBufferSizeInBytes | Buffer size for socket operations |
| SocketTimeoutInMillis | Timeout for socket data transmission (unit: ms) |
| StreamBufferSize | Stream file buffer size |
| UserAgent | User agent, refers to HTTP’s User-Agent header |
| RedirectsEnabled | Option to enable HTTP redirection, which is disabled by default. |
| MaxRedirects | Defines the maximum number of automatic HTTP redirects, which is set to 1 by default. |
| PathStyleAccessEnable | Whether to use PathStyle-style endpoints, disabled by default, that is, using bucket virtual hosting |
