All Products
Search
Document Center

Object Storage Service:Pertanyaan yang Sering Diajukan (Android SDK)

Last Updated:Jun 11, 2026

Masalah umum dan solusi untuk OSS SDK untuk Android.

Catatan

Sebelum menggunakan kode contoh, Anda harus menginstal HTTPDNS SDK untuk Android. Untuk informasi selengkapnya, lihat Install HTTPDNS SDK for Android.

Apakah OSS SDK untuk Android mendukung pre-resolusi DNS dan kebijakan cache?

Ya. Gunakan HTTPDNS SDK dan OkHttp secara bersamaan untuk menerapkan pre-resolusi dan caching DNS.

  1. Implementasikan API untuk layanan resolusi DNS kustom.

    public class OkHttpDns implements Dns {
        private static final Dns SYSTEM = Dns.SYSTEM;
        HttpDnsService httpdns;
        private static OkHttpDns instance = null;
        private OkHttpDns(Context context) {
            this.httpdns = HttpDns.getService(context, "account id");
        }
        public static OkHttpDns getInstance(Context context) {
            if(instance == null) {
                instance = new OkHttpDns(context);
            }
            return instance;
        }
        @Override
        public List<InetAddress> lookup(String hostname) throws UnknownHostException {
            // Gunakan API resolusi asinkron untuk mendapatkan alamat IP.
            String ip = httpdns.getIpByHostAsync(hostname);
            if(ip != null) {
                // Alamat IP berhasil diresolusi — gunakan untuk permintaan jaringan.
                List<InetAddress> inetAddresses = Arrays.asList(InetAddress.getAllByName(ip));
                Log.e("OkHttpDns", "inetAddresses:" + inetAddresses);
                return inetAddresses;
            }
            // Tidak ada alamat IP yang diresolusi — kembali ke layanan DNS sistem.
            return Dns.SYSTEM.lookup(hostname);
        }
    }
  2. Buat instans OkHttpClient dan konfigurasikan pre-resolusi serta caching DNS.

    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    ClientConfiguration conf = new ClientConfiguration();
    conf.setConnectionTimeout(15 * 1000); // Connection timeout. Default: 15 seconds.
    conf.setSocketTimeout(15 * 1000); // Socket timeout. Default: 15 seconds.
    conf.setMaxConcurrentRequest(5); // Maximum concurrent requests. Default: 5.
    conf.setMaxErrorRetry(2); // Maximum retries. Default: 2.
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .dns(OkHttpDns.getInstance(getApplicationContext()));
    // Jika Anda menyetel OkHttpClient kustom, beberapa pengaturan ClientConfiguration akan ditimpa.
    // Tetapkan pengaturan tersebut langsung pada builder.
    if (conf != null) {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(conf.getMaxConcurrentRequest());
        builder.connectTimeout(conf.getConnectionTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(conf.getSocketTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(conf.getSocketTimeout(), TimeUnit.MILLISECONDS)
                .followRedirects(conf.isFollowRedirectsEnable())
                .followSslRedirects(conf.isFollowRedirectsEnable())
                .dispatcher(dispatcher);
        if (conf.getProxyHost() != null && conf.getProxyPort() != 0) {
            builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(conf.getProxyHost(), conf.getProxyPort())));
        }
    }
    // Android SDK 2.9.12 dan versi lebih baru mendukung conf.setOkHttpClient().
    conf.setOkHttpClient(builder.build());
    OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);

Mengapa callback progress mengembalikan totalSize=-1 saat mengunduh objek?

  • Penyebab: Saat OkHttp mengunduh objek dengan tipe konten tertentu (text/cache-manifest, text/xml, text/plain, text/css, application/javascript, application/x-javascript, application/rss+xml, application/json, text/json) yang berukuran 1 KB atau lebih besar, header Accept-Encoding: gzip secara otomatis ditambahkan—meskipun Anda tidak menyetelnya. OSS kemudian mengembalikan objek dalam format gzip tanpa header Content-Length, sehingga menyebabkan callback progress melaporkan totalSize=-1.

  • Solusi: Tetapkan header Range pada permintaan. Hal ini mencegah OkHttp menambahkan Accept-Encoding: gzip, sehingga OSS mengembalikan Content-Length dan callback progress melaporkan ukuran yang benar.

    Map<String, String> header = new HashMap<>();
    header.put("x-oss-range-behavior", "standard");
    // Ganti examplebucket dengan nama bucket Anda dan exampledir/exampleobject.txt dengan path lengkap objek.
    GetObjectRequest get = new GetObjectRequest("examplebucket", "exampledir/exampleobject.txt");
    get.setRange(new Range(0, -1));
    get.setRequestHeaders(header);
    OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
        @Override
        public void onSuccess(GetObjectRequest request, GetObjectResult result) {
            InputStream inputStream = result.getObjectContent();
            byte[] buffer = new byte[2048];
            int len;
            try {
                while ((len = inputStream.read(buffer)) != -1) {
                    // Proses data yang diunduh.
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
            if (clientExcepion != null) {
                // Tangani exception lokal, seperti error jaringan.
                clientExcepion.printStackTrace();
            }
            if (serviceException != null) {
                // Tangani exception layanan.
                Log.e("ErrorCode", serviceException.getErrorCode());
                Log.e("RequestId", serviceException.getRequestId());
                Log.e("HostId", serviceException.getHostId());
                Log.e("RawMessage", serviceException.getRawMessage());
            }
        }
    });

onFailure callback tidak dipicu di Kotlin

  • Penyebab

Ini merupakan masalah nullability di Kotlin. OSS Android SDK mendefinisikan callback onFailure menggunakan sintaksis Java, di mana parameter secara default tidak nullable:

@Override
public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException){
    if (clientException != null) {
        clientException.printStackTrace();
    }
    if (serviceException != null) {
        Log.e("ErrorCode", serviceException.getErrorCode());
        Log.e("RequestId", serviceException.getRequestId());
        Log.e("HostId", serviceException.getHostId());
        Log.e("RawMessage", serviceException.getRawMessage());
    }
}

Kotlin memperlakukan parameter tersebut sebagai non-nullable, sehingga callback mungkin tidak dipicu sebagaimana mestinya. Secara eksplisit deklarasikan parameter sebagai nullable dalam signature fungsi:

onFailure(request: ResumableUploadRequest, clientException: ClientException?, serviceException: ServiceException?)