Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects

Overview

KNet

License: MIT

Android network client based on Cronet. This library let you easily use QUIC protocol in your Android projects. You can see more about QUIC here - mobile or product or backend

Order:

Cronet wrapper improvements:

  • Memory Optimizations
  • Multithreading Optimizations
  • Redirects Settings
  • Quic Configurations
  • Timeouts Settings
  • Broken Hosts Clearing
  • Documentation
  • Interceptor System
  • Debug System
  • Metrics
  • Error Handling
  • (soon) Fallback System
  • (soon) Encodings
  • (soon) Tests
  • (soon) Integrations(ExoPlayer/Ktor/Okhttp/Flipper/Stetho)
  • (soon) Backoff
  • (soon) DNS Prefetch

Gradle

You can try this library using Gradle:

dependencies {
 implementation 'com.vk.knet:core:1.0-alpha02'
 implementation 'com.vk.knet:cronet:1.0-alpha02'
 implementation 'com.vk.knet:okcronet:1.0-alpha02'
}

Initialization

Short version:

val cronet = CronetKnetEngine.Build(App.context) {
    client {
        enableQuic(
            CronetQuic(hints = listOf(Host("drive.google.com", 443)))
        )
    }
}

val knetCronet = Knet.Build(cronet)

Full version:

Metrics.addMetric(metric) } } addInterceptor { p -> try { p.proceed(p.request) } catch (e: Exception) { try { println("[KNet] [RETRY ${if (e is ConnectException) e.message else e.localizedMessage}]") p.proceed(p.request) } catch (e: Exception) { e.printStackTrace() throw e } } } } val knetCronet = Knet.Build(cronet) { bufferPool(ByteArrayPool.DEFAULT) } ">
CronetLogger.global(
    object : CronetHttpLogger {
        override fun error(vararg obj: Any) {
            Log.e("Logos", obj.toList().toString())
        }

        override fun debug(type: CronetHttpLogger.DebugType, vararg obj: Any) {
            Log.d("[${type.name}]", obj.toList().toString())
        }

        override fun info(vararg obj: Any) {
            Log.i("Logos", obj.toList().toString())
        }
    }
)

private val cronet = CronetKnetEngine.Build(App.context) {
    client {
        setCache(CronetCache.Disk(App.context.filesDir, 1024 * 1024 * 10))

        enableHttp2(true)
        enableQuic(
            CronetQuic(
                hints = listOf(
                    Host("drive.google.com", 443)
                ),
            )
        )

        useBrotli(true)
        isClearBrokenHosts(true)

        netlog(CronetLog.Config(netDir, 1024 * 1024 * 100))

        connectTimeout(15, TimeUnit.SECONDS)
        writeTimeout(15, TimeUnit.SECONDS)
        readTimeout(15, TimeUnit.SECONDS)

        nativePool(CronetNativeByteBufferPool.DEFAULT)
        arrayPool(ByteArrayPool.DEFAULT)

        maxConcurrentRequests(50)
        maxConcurrentRequestsPerHost(10)

        followRedirects(true)
        followSslRedirects(true)

        addMetricListener { metric: HttpMetrics, _, _ ->
            Metrics.addMetric(metric)
        }
    }

    addInterceptor { p ->
        try {
            p.proceed(p.request)
        } catch (e: Exception) {
            try {
                println("[KNet] [RETRY ${if (e is ConnectException) e.message else e.localizedMessage}]")
                p.proceed(p.request)
            } catch (e: Exception) {
                e.printStackTrace()
                throw e
            }
        }
    }
}

val knetCronet = Knet.Build(cronet) {
    bufferPool(ByteArrayPool.DEFAULT)
}

OkHTTP

If you're now using OkHttp, you can simply wrap KNet into OkHttp Interceptor... Easy, right?

val knetCronet = Knet.Build(cronet)
val okhttpInterceptor = KnetToOkHttpInterceptor(knetCronet)

val builder = OkHttpClient.Builder()
builder.addInterceptor(okhttpInterceptor)
val client = builder.build()

Comming Soon

  • Tests
  • Exo
  • Ktor
  • OkHttp
  • Flipper
  • Stetho

Licence

The MIT License (MIT)

Copyright (c) 2019 vk.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You might also like...
Operations are performed by calling api endpoints over the network

##About The app Operations are performed by calling api endpoints over the network. Local data is in effect immutable, the client just downloads updat

SMNetworkChecker aims to help check if the network is connected or if the wifi is connected.
SMNetworkChecker aims to help check if the network is connected or if the wifi is connected.

Network Checker for Android SMNetworkChecker aims to help check if the network is connected or if the wifi is connected. Preview Network connection O

 Ktor-Client  this is the client part that uses the Ktor server
Ktor-Client this is the client part that uses the Ktor server

Ktor-Client this is the client part that uses the Ktor server Previews Tech stack & Open source libraries Minimum SDK level 21. Kotlin+ Coroutines + F

Simple kafka client for monitoring topic events. Client has UI powered by Darklaf
Simple kafka client for monitoring topic events. Client has UI powered by Darklaf

kafka-client Simple kafka client for monitoring topic values. How to start $ java -jar kafka-client-1.0.jar How to use specify kafka hosts in config.y

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

AndroidAsync AndroidAsync is a low level network protocol library. If you are looking for an easy to use, higher level, Android aware, http request li

Multiplatform coroutine-based HTTP client wrapper for Kotlin

networkinkt This is a lightweight HTTP client for Kotlin. It relies on coroutines on both JS & JVM platforms. Here is a simple GET request: val text =

A gRPC Kotlin based server and client starter that builds with Gradle and runs on the JVM
A gRPC Kotlin based server and client starter that builds with Gradle and runs on the JVM

gRPC Kotlin starter Overview This directory contains a simple bar service written as a Kotlin gRPC example. You can find detailed instructions for bui

A Kotlin client for the gRPC based Bar Service
A Kotlin client for the gRPC based Bar Service

Bar Service Kotlin Client Overview This directory contains a simple bar service client written in Kotlin against generated models (protos) You can fin

Light library to check internet connection in android apps easily.
Light library to check internet connection in android apps easily.

check-internet-android Light library to check internet connection in android apps easily. It checks real internet connection by connecting to Google's

Comments
  • Proguard rules

    Proguard rules

    Какие rules надо для proguard? С proguard получаю ошибку java.lang.RuntimeException: Unable to find any Cronet provider. Have you included all necessary jars? Пробовал

    -keep class org.chromium.net.impl.NativeCronetProvider {
        public <init>(android.content.Context);
    }
    

    С таким правилом получаю java.lang.UnsatisfiedLinkError: JNI_ERR returned from JNI_OnLoad in "/data/app/apppackage/lib/arm64/libcronet.93.0.4577.82.so"

    opened by Snowmaze-dev 9
  • 64-bit x86 Support

    64-bit x86 Support

    Hi, we have noticed that this project does not include an x86_64 binary. This is required for Chromebooks and other devices. Crash report for reference:

    2021-11-17 14:12:33.413 6772-6772/com.example E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example, PID: 6772 java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.example-4ObnE4hgI7tCiid5nvokZw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example-4ObnE4hgI7tCiid5nvokZw==/lib/x86_64, /data/app/com.example-4ObnE4hgI7tCiid5nvokZw==/base.apk!/lib/x86_64, /system/lib64, /vendor/lib64]]] couldn't find "libcronet.93.0.4577.82.so" at java.lang.Runtime.loadLibrary0(Runtime.java:1012) at java.lang.System.loadLibrary(System.java:1669) at org.chromium.net.impl.CronetLibraryLoader.ensureInitialized(CronetLibraryLoader.java:71) at org.chromium.net.impl.CronetUrlRequestContext.<init>(CronetUrlRequestContext.java:154) at org.chromium.net.impl.NativeCronetEngineBuilderImpl.build(NativeCronetEngineBuilderImpl.java:32) at org.chromium.net.ExperimentalCronetEngine$Builder.build(ExperimentalCronetEngine.java:232) at com.vk.knet.cornet.CronetEngineBuilder.build(CronetEngineBuilder.kt:234) at com.vk.knet.cornet.experiment.CronetClient$Builder.cronetEngine(CronetClient.kt:507) at com.vk.knet.cornet.experiment.CronetClient$Builder.build$cronet_release(CronetClient.kt:440) at com.vk.knet.cornet.CronetKnetEngine$Builder.build$cronet_release(CronetKnetEngine.kt:82) at com.vk.knet.cornet.CronetKnetEngine$Companion.Build(CronetKnetEngine.kt:45) at com.example.Utils.KnetCronet.<clinit>(KnetCronet.kt:16) at com.example.Core.Application.onCreate(Application.java:156) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1167) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6130) at android.app.ActivityThread.access$1100(ActivityThread.java:201) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1725) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6971) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:865)

    opened by CWftw 2
  • Put Request Missing Body

    Put Request Missing Body

    Hi, looks like if the http request is a PUT the request is missing a body?

    https://github.com/VKCOM/KNet/blob/7949275942fbde863bd0971f0efa6307cefc25d3/knet/okcronet/src/main/java/com/vk/knet/okcronet/ExtensionAdapters.kt#L67

    opened by GEverding 2
  • APK стал весить на 6 мб больше

    APK стал весить на 6 мб больше

    Раньше пробовал Cronet отдельно и размер apk рос буквально на 200 кб, сейчас размер apk растёт с 2 мб до 8 мб. В частности из-за либ Cronet, которые 12мб в распакованном состоянии весят. Так и должно быть? image

    opened by Snowmaze-dev 2
Owner
VK.com
VK.com
SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network requests with HttpURLConnection.

SimpleApiCalls ?? SimpleApiCalls is a type-safe REST client for Android. The library provides the ability to interact with APIs and send network reque

null 4 Nov 28, 2022
A library that observes your network status.

A library that observes your network status. Update in progress ... Download Using gradle In your root build.gradle at the end of repositories add all

Moses Wangira 9 Apr 18, 2022
Compact and easy to use, 'all-in-one' android network solution

Deprecated Unfortunately due to many reasons including maintenance cost, this library is deprecated. I recommend to use Retrofit/OkHttp instead. Curre

Orhan Obut 585 Dec 30, 2022
Cli lightning network server, based on LDK (rust-lightning). Provides DUMB-RPC interface (telnet friendly).

Hello Lightning Cli lightning network server, based on LDK (rust-lightning). Provides DUMB-RPC interface (telnet friendly). Example: Build it run it:

null 9 Mar 28, 2022
Write your asynchronous Network / IO call painlessly in Kotlin !!

Asynkio : Write asynced IO/ Network calls painlessly on android | | | Documentation Write your network requests, IO calls in android with Kotlin seaml

Nikhil Chaudhari 82 Jan 26, 2022
Android library listening network connection state and change of the WiFi signal strength with event bus

NetworkEvents Android library listening network connection state and change of the WiFi signal strength with event bus. It works with any implementati

Piotr Wittchen 452 Nov 21, 2022
HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps

HttpMocker HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries. It ca

David Blanc 174 Nov 28, 2022
Kotlin-echo-client - Echo client using Kotlin with Ktor networking library

Overview This repository contains an echo server implemented with Kotlin and kto

Elliot Barlas 2 Sep 1, 2022
Sandwich was invented for constructing the standardized response interface from the network response

?? A lightweight and standardized Android network response interface for handling successful data and error responses.

Jaewoong Eum 973 Jan 5, 2023