This topic describes how to use mobile apps such as OssDemo to upload data to OSS through an existing app server when you do not need to store AccessKey IDs and AccessKey secrets in the app.

Processing logic

  1. OssDemo sends a request after obtaining the address of sts_server.
  2. sts_server returns AccessKeyId, AccessKeySecret, SecurityToken, and Expiration.
  3. After obtaining the information, OssDemo calls the SDK to create OSSClient.

Code analysis

  1. Generate an EditText control.
    Location:
     res/layout/content_main.xml
     Content:
     <EditText
         android:layout_height="wrap_content"
         android:layout_width="0dp"
         android:layout_weight="4"
         android:id="@+id/sts_server"
         android:text="@string/sts_server"
         />
     Location:
     res/values/strings
     Content:
     <string name="sts_server">http://oss-demo.aliyuncs.com/app-server/sts.php</string>
  2. Obtain the code related to STS parameters from the app server.
    Function implementation:
    OSSFederationToken getFederationToken()
  3. Call the STS response parameters to initialize OSSClient.
    Function implementation:
    //Initialize OssService for uploads and downloads.
     public OssService initOSS(String endpoint, String bucket, ImageDisplayer displayer) {
         //To use an AccessKey pair for access, use OSSPlainTextAKSKCredentialProvider for authentication.
         //OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
         // Use your own class to obtain the STSToken.
         OSSCredentialProvider credentialProvider = new STSGetter(stsServer);
         ClientConfiguration conf = new ClientConfiguration();
         conf.setConnectionTimeout(15 * 1000); // Connection timeout period in seconds. Default value: 15
         conf.setSocketTimeout(15 * 1000); // Socket timeout period in seconds. Default value: 15
         conf.setMaxConcurrentRequest(5); // Maximum concurrent requests. Default value: 5
         conf.setMaxErrorRetry(2); // Maximum retry attempts after failures. Default value: 2
         OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
         return new OssService(oss, bucket, displayer);
     }