java.net.UnknownServiceException: CLEARTEXT communication to t.main.wedeep.com.cn not permitted by network security policy
Asked Answered
E

2

7

I got above error when i use mockhttpserver to test http request, the following code is how i create service.

   fun <T> getService(clazz: Class<T>): T {
        val client = OkHttpClient.Builder().addInterceptor(HeaderInterceptor()).addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE })
                .build()
        return Retrofit.Builder()
                .baseUrl(mockWebServer.url(""))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GSON))
                .build()
                .create(clazz)
    }

This is my Test code.

@UninstallModules(HomePageDataModule::class)
@HiltAndroidTest
class TestHomePageViewModel {


    private lateinit var viewModel: HomePageViewModel

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    @Inject
    lateinit var cpd: CompositionDao

    @Inject
    lateinit var csd: CompositionsDao

    @Inject
    lateinit var hpds: HomePageDataSource

    @Inject
    lateinit var ss :HomePageService

    @Before
    fun init() {
        hiltRule.inject()
        viewModel = HomePageViewModel(HomeCompositionsRepository(cpd, csd, hpds, Util.GSON))

    }





    @Test
    fun testObserveHomeData() {

        val data = Util.getFileString("mainpage.json")
        val rr  = GSON.fromJson(data,Array<HomePreviewView>::class.java)
        println(rr)
        enqueueResponse("mainpage.json")
        runBlocking {
            val result = ss.getHomeData()
            Assert.assertNotEquals(rr.size,result.body()!!.size)
        }
}

Everything works smoothly on my app except running my unit test code. There is a similar problem , but my issue has a little difference compare to that one. Plenty of ways from that similar question i have tried, but not work.

PS: If the test code run on Junit4Test but not AndroidJunit4Test, it works properly. But now i need to exectue a integrate test. So this part of code need to be executed on AndroidJunit4Test

Esophagus answered 22/7, 2020 at 10:20 Comment(6)
Make sure your host is secure for your application or you can just add this line of code inside your manifest file. android:usesCleartextTraffic="true"Corporator
@AslamHossin I have no idea why it does not work for me when i execute above unit test code.Esophagus
#53985225Intensive
Does this answer your question? Android 8: Cleartext HTTP traffic not permittedConsumerism
@Esophagus When the attribute is set to "false", platform components (for example, HTTP and FTP stacks, DownloadManager, and MediaPlayer) will refuse the app's requests to use cleartext traffic. Third-party libraries are strongly encouraged to honor this setting as well. The key reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected. More developer.android.com/guide/topics/manifest/…Corporator
You can also use mockWebServer.useTls and client.insecureHost to use SSL for the test connections.Anesthesiology
I
23

Solution 1)

Add the following attribute to the <application tag in AndroidManifest.xml:

android:usesCleartextTraffic="true"

Solution 2)

Add android:networkSecurityConfig="@xml/network_security_config" to the <application tag in app/src/main/AndroidManifest.xml:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:theme="@style/AppTheme">

With a corresponding network_security_config.xml in app/src/main/res/xml/:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>
Intensive answered 22/7, 2020 at 10:37 Comment(2)
Post the error , also shared other details like device , sdk etcIntensive
I don't know why but just solution2 worked for me in api 30Osana
W
3

In my case, I added this to the android manifest file:

android:usesCleartextTraffic="true"

Waterlogged answered 2/1, 2021 at 22:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.