Меню

Ошибка net err cleartext not permitted

How goes your app’s development? Are you receiving the error message “net::err_cleartext_not_permitted”? Well, good thing this article contains four great solutions to solve your Android Webview issue. We’ll cover what this error means and how you can solve the root problem. Continue reading below for some useful background information, causes of this error, and of course, the solutions.

net::err_cleartext_not_permitted error message on Android

What is Android Webview?

Android is an operating system with 87% of the global market share for mobile devices. As a result, Android applications can reach a much larger audience than applications designed for Apple. Additionally, it’s more difficult to be approved on Apple’s App Store than Google Play. For this reason, many application developers opt to focus on Android development.

Android WebView is a view used by developers to include functional web content into their applications. Android WebView isn’t a fascinating component, but it’s an integral Android development tool. Android WebView now updates independently of Android, and Google recommends all users update WebViews as updates become available. One downside to Webview is that any major outages or update issues will be experienced on any apps developed to use Webview. To prevent security issues, users should keep their Android operating system updated, as patches are no longer rolled out for Android version 4.3 and below.

On any Android phone, Webview is the only method to view content on the internet outside of a web browser. To contain all user actions within an application, a developer can implement Webview. For example, when a user clicks a link inside an application, the site will be loaded within the application instead of opening a pop-up web browser.

Cleartext is any information that has not been encrypted. As such, there is no need to decrypt the data to read it. Cleartext differs from plaintext, which is just plain language that might have been encrypted at some point. Information sent over the internet using cleartext can be subject to malicious attacks. The cleartext information may be stolen or manipulated.

To prevent tampering and other malicious activity, especially as cleartext data interacts with third-party servers, Google decided to disable cleartext information by default. Google implemented this change on Android 9 (API 28).

Note: Android 9 Pie was released on August 6th, 2018. Currently, the Android operating system is on version 11 (API 30).

Cleartext is typically sent over an HTTP (hypertext transfer protocol) URL. Following the Android 9 update, all applications using Android Webview should use HTTPS; otherwise, the system will throw the net::err_cleartext_not_permitted error. In short, this error will appear to users of your application because of Android’s network security configuration when accessing HTTP URLs.

How to solve the net::err_cleartext_not_permitted Android Webview error

Developers can solve the net::err_cleartext_not_permitted Android Webview error by allowing only HTTPS URLs in their application. Any website with a valid SSL certificate can be accessed using HTTPS. Therefore, you need to remove all unsecured URLs and force HTTPS for all websites.

Before proceeding to solutions to force HTTPS, you’ll learn a quick workaround. This option is available if you are unable to force all connections:

1. Edit AndroidManifest.xml

All Android applications will have an AndroidManifest.xml file. This file contains vital information about your application, such as activities and services. AndroidManifest.xml also provides permissions for protected parts of the application and declares the application’s Android API.

You are going to edit the application subelement (within manifest). You will be adding a simple application tag.

Warning: This workaround should only be a temporary fix, as it will compromise your user’s data integrity due to the major vulnerability posed by cleartext data over HTTP URLs.

Here is how to edit the AndroidManifes.xml:

  1. Find AndroidManifest.xml file in application folder at:
    android/app/src/main/AndroidManifest.xml
  2. Locate the application subelement.
  3. Add the following tag:
    android:usesCleartextTraffic=”true”
  4. The application subelement should now look like:
<application
    android:name=”io.flutter.app.Test”
    android:label=”bell_ui”
    android:icon=”@mapmap/ic_launcher”
    android:usesCleartextTraffic=”true”>
  1. Save the AndroidManifest.xml file.

The following two solutions will involve forcing HTTPS on either WordPress or HTML/PHP sites. If you are building an Android application to accompany a web application (there are many reasons to develop a native app), then you will anticipate much overlap in URLs. You can edit your website to force HTTPS usage as long as you have an SSL certificate installed.

2. Force HTTPS for WordPress Sites

To force HTTPS on a WordPress site, you will need to edit the .htaccess file. The .htaccess file is involved in managing redirects and permalinks.

  1. Login to your WordPress admin dashboard.
  2. Select Settings and then General from the left-hand dashboard.
General Settings
  1. Locate WordPress Address (URL) and Site Address (URL) and make sure these URLs are HTTPS. Your site will need an SSL certificate for this. 
  2. Now, you will need access to a file manager through FTP or cPanel to edit your WordPress files. There are alternative options, such as plugins that can also provide this functionality. Locate the .htaccess file within the root folder and Open the file.
.htaccess file
  1. Within this file locate # BEGIN WordPress. This is the start of the WordPress rules that you are going to edit. Replace that entire section, ending with # END WordPress, with the following text. Be sure to replace the XXXX with your own domain name but do not rearrange the text in any other way:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ – [L]

# Rewrite HTTP to HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://XXXX.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
  1. Make sure to save your changes to the .htaccess file.

3. Force HTTPS for HTML/PHP Sites

  1. Open FTP or cPanel and access the root directory for your site.
  2. If you are in cPanel you can click the + File button on the top toolbar. In FTP you can right-click inside the root directory and select Create new file. Create a file called .htaccess.

cPanel:

cPanel File Manager

FTP:

Remote Site - Create new file
  1. Now open the .htaccess file that was created in the root directory.
  2. If your site uses a www address then add the following block of code to your .htaccess file:
RewriteEngine On

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  1. If your site uses a non-www address then add the following block of code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^(www.)(.+) [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]
  1. If your site uses PHP you will also need to update your PHP Config file, site URL, and base URL variables.

4. Edit network_security_config.xml

This next solution is available for applications using Android version 7 or above. The network_security_config.xml file allows developers to edit the network security configuration to suit their application’s needs. You can edit this file to allow a specific domain name to bypass the security rules. Network traffic using this domain would not trigger the net::err_cleartext_not_permitted error.

To add a domain to the whitelist:

  1. Inside your Android application folder, add a file named network_security_config.xml at the following location:
    res/xml/
  2. Add the following domain configuration text. Make sure to change the your_domain.com part to your website’s address.
<?xml version=”1.0″ encoding=”utf-8″?>
<network-security-config>
    <domain-config cleartextTrafficPermitted=”true”>
        <domain includeSubdomains=”true”>your_domain.com</domain>
    </domain-config>
</network-security-config>
  1. Save the changes to the network_security_config.xml file.
  2. Find AndroidManifest.xml file in the application folder at:
    android/app/src/main/AndroidManifest.xml
  3. Locate the application subelement.
  4. Add the following text to specify the path to the network security configuration file:
<application

    android:name=”.DemoApp”
    android:networkSecurityConfig=”@xml/network_security_config”

net::err_cleartext_not_permitted Android Webview error solved

Android Webview is an excellent system component for any Android developer to have in their toolkit. Webview allows a developer to display web content, like your own or a third-party website, within the native application. If Webview is not used, the only method to display web content involves a disruption in the usage of the application. A browser, a completely different application, will open. Once a user leaves your application, they may never return. This can result in less traffic, ad revenue, and sales.

If you followed the solutions above, you would have edited your application’s AndroidManifest.xml file to add an exception for cleartext traffic. You have created and edited a network_security_config.xml file to whitelist a specific domain for cleartext network traffic.

If you are developing an application with significant URL overlap as a web application, then solutions 2 and 3 are especially useful. You learned how to force the use of HTTPS for either a WordPress or an HTML/PHP web application. It is done by editing the .htaccess file using cPanel or FTP.

If you would like to learn more about Android Network Security configuration and specifically cleartext traffic rules, you can do so here.

If you want to learn more about Android Webview, you can do so here. The documentation is excellent, and you will have a far better understanding of Android Webview if you read the documentation. As you learned above, there are some constraints associated with Webview.

You might also experience related Android WebView errors while building your app. However, there is no need to worry because we have covered the other common WebView error message, err_unknown_url_scheme, in a separate article.

After upgrading to Cordova Android 8.0, I am seeing net::ERR_CLEARTEXT_NOT_PERMITTED errors when trying to connect to http:// targets.

Why is that and how can I resolve this?

asked Feb 18, 2019 at 17:44

Oliver Salzburg's user avatar

Oliver SalzburgOliver Salzburg

21.3k19 gold badges92 silver badges136 bronze badges

0

The default API level in the Cordova Android platform has been upgraded. On an Android 9 device, clear text communication is now disabled by default.

To allow clear text communication again, set the android:usesCleartextTraffic on your application tag to true:

<platform name="android">
  <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
      <application android:usesCleartextTraffic="true" />
  </edit-config>
</platform>

As noted in the comments, if you have not defined the android XML namespace previously, you will receive an error: unbound prefix during build. This indicates that you need to add it to your widget tag in the same config.xml, like so:

<widget id="you-app-id" version="1.2.3"
xmlns="http://www.w3.org/ns/widgets" 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">

answered Feb 18, 2019 at 17:44

Oliver Salzburg's user avatar

Oliver SalzburgOliver Salzburg

21.3k19 gold badges92 silver badges136 bronze badges

11

There are two things to correct in config.xml
So the right answer should be adding the xmls:android:

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

plus editing the config to allow:

<platform name="android">
  <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
      <application android:usesCleartextTraffic="true" />
  </edit-config>
</platform>

If step 1 is avoided error: unbound prefix. will appear

answered May 22, 2019 at 18:07

zardilior's user avatar

zardiliorzardilior

2,66224 silver badges29 bronze badges

1

Cleartext here represents unencrypted information. Since Android 9, it is recommended that apps should call HTTPS APIs to make sure there is no eves dropping.

However, if we still need to call HTTP APIs, we can do following:

Platform: Ionic 4

Create a file named: network_security_config.xml under project-root/resources/android/xml

Add following lines:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <domain-config cleartextTrafficPermitted="true">
     <domain>ip-or-domain-name</domain>
   </domain-config>
</network-security-config>

Now in project-root/config.xml, update following lines:

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ... other statements...

It should work now.

answered Jul 19, 2019 at 9:01

Ashutosh's user avatar

AshutoshAshutosh

4,17910 gold badges56 silver badges98 bronze badges

5

To solve the problem there’s other option.
in file resources/android/xml/network_security_config.xml. insert:

<network-security-config>
   <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
           <certificates src="system" />
       </trust-anchors>
   </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain>localhost</domain>
        <domain includeSubdomains="true">192.168.7.213:8733</domain>
    </domain-config>
</network-security-config>

Im my case I´m using IP address then base-config is necessary, but if you have a domain. just add the domain.

answered Jun 7, 2019 at 12:12

Edvan Souza's user avatar

Edvan SouzaEdvan Souza

1,0509 silver badges11 bronze badges

2

I ran into this problem myself today, and found a really nifty plugin that will save you the hassle of trying to manually allow cleartext traffic in Android 9+ for your Apache Cordova application. Simply install cordova-plugin-cleartext, and the plugin should take care of all the behind the scenes Android stuff for you.

$ cordova plugin add cordova-plugin-cleartext
$ cordova prepare
$ cordova run android

answered Nov 17, 2019 at 2:18

topherPedersen's user avatar

3

After a few days of struggle, this works for me, and I hope this also works for you.

add this to your CONFIG.XML, top of your code.

<access origin="*" />
<allow-navigation href="*" />

and this, under the platform android.

<edit-config file="app/src/main/AndroidManifest.xml" 
   mode="merge" target="/manifest/application" 
   xmlns:android="http://schemas.android.com/apk/res/android">
     <application android:usesCleartextTraffic="true" />
     <application android:networkSecurityConfig="@xml/network_security_config" />
 </edit-config>
 <resource-file src="resources/android/xml/network_security_config.xml" 
 target="app/src/main/res/xml/network_security_config.xml" />

add the follow code to this file «resources/android/xml/network_security_config.xml».

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">YOUR DOMAIN HERE/IP</domain>
    </domain-config>
</network-security-config>

enter image description here

enter image description here

answered Nov 16, 2019 at 15:50

Sushil's user avatar

SushilSushil

2,21526 silver badges24 bronze badges

6

Adding the following attribute within the opening < widget > tag worked for me. Simple and live reloads correctly on a Android 9 emulator. xmlns:android=»http://schemas.android.com/apk/res/android»

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

answered Apr 21, 2019 at 21:49

Mark McCorkle's user avatar

Mark McCorkleMark McCorkle

9,3392 gold badges32 silver badges42 bronze badges

3

Im using IONIC 5.4.13, cordova 9.0.0 (cordova-lib@9.0.1)

I might be repeating information but for me problem started appearing after adding some plugin (not sure yet).
I tried all above combinations, but nothing worked.
It only started working after adding:

   <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
           <certificates src="system" />
       </trust-anchors>
   </base-config>

to file in project at

resources/android/xml/network_security_config.xml

so my network_security_config.xml file now looks like:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <base-config cleartextTrafficPermitted="true">
       <trust-anchors>
           <certificates src="system" />
       </trust-anchors>
   </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.1.25.10</domain>
    </domain-config>
</network-security-config>

Thanks to all.

answered Jan 22, 2020 at 9:36

Rajendra's user avatar

RajendraRajendra

97912 silver badges20 bronze badges

9

After reading the whole discussion looking for a way to authorize communication to all IP addresses as in my case the IP address to where the request will be sent is defined by the user in an input text and can not be defined in the configuration file. Here is how I resolved the issue

here are the configuration

config.xml

<platform name="android">
...
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:networkSecurityConfig="@xml/network_security_config" />
        </edit-config>
        <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
...
</platform>

resources/android/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

The most important piece of code is <base-config cleartextTrafficPermitted="true" /> in <network-security-config> instead of domain-config

answered Nov 11, 2020 at 10:02

stodi's user avatar

stodistodi

1,46912 silver badges22 bronze badges

1

you should add

<base-config cleartextTrafficPermitted="true">
    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
</base-config>

to

resources/android/xml/network_security_config.xml

like this

<network-security-config>
<base-config cleartextTrafficPermitted="true">
    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
</base-config>

<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">localhost</domain>
</domain-config> </network-security-config>

answered Aug 18, 2019 at 15:59

mustafa mohamed's user avatar

2

Just add this line to platforms/android/app/src/main/AndroidManifest.xml file

<application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" **android:usesCleartextTraffic="true"**>

answered Jul 19, 2020 at 6:49

Manoj Alwis's user avatar

Manoj AlwisManoj Alwis

1,24111 silver badges23 bronze badges

0

Following is the solution which worked for me. The files which I updated are as follows:

  1. config.xml (Full Path: /config.xml)
  2. network_security_config.xml (Full Path: /resources/android/xml/network_security_config.xml)

Changes in the corresponding files are as follows:

1. config.xml

I have added <application android:usesCleartextTraffic="true" /> tag within <edit-config> tag in the config.xml file

<platform name="android">
    <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
        <application android:usesCleartextTraffic="true" />
        <application android:networkSecurityConfig="@xml/network_security_config" />
    </edit-config>
    ...
<platform name="android">

2. network_security_config.xml

In this file I have added 2 <domain> tag within <domain-config> tag, the main domain and a sub domain as per my project requirement

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">mywebsite.in</domain>
        <domain includeSubdomains="true">api.mywebsite.in</domain>
    </domain-config>
</network-security-config>

Thanks @Ashutosh for the providing the help.

Hope it helps.

answered Nov 7, 2019 at 13:30

Zaki Mohammed's user avatar

0

Following solution worked for me-

goto resources/android/xml/network_security_config.xml
Change it to-

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">api.example.com(to be adjusted)</domain>
    </domain-config>
</network-security-config>

answered Apr 1, 2020 at 8:33

Leena's user avatar

LeenaLeena

6371 gold badge11 silver badges19 bronze badges

Old ionic cli (4.2) was causing issue in my case, update to 5 solve the problem

answered Jul 3, 2019 at 21:58

hugo blanc's user avatar

hugo blanchugo blanc

2713 silver badges13 bronze badges

1

I am running Ionic 5 with Vue and Capacitor 3 and was getting this error using the InAppBrowser for a website that doesn’t support https. For Capacitor apps, config.xml isn’t used and AndroidManifest.xml is edited directly.

First, create the Network Security Config file here YOUR_IONIC_APP_ROOTandroidappmainresxmlnetwork_security_config.xml.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <domain-config cleartextTrafficPermitted="true">
        <domain>www.example.com</domain>
   </domain-config>
</network-security-config>

Then edit YOUR_IONIC_APP_ROOTandroidappmainAndroidManifest.xml adding android:networkSecurityConfig="@xml/network_security_config" to application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.ionic.starter">

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

        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- ... -->
    </application>
    <!-- ... -->
</manifest>

answered Apr 16, 2021 at 14:34

wsamoht's user avatar

wsamohtwsamoht

1,5281 gold badge14 silver badges14 bronze badges

@Der Hochstapler thanks for the solution.
but in IONIC 4 some customization in project config.xml work for me

Add a line in Widget tag

<widget id="com.my.awesomeapp" version="1.0.0" 
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:cdv="http://cordova.apache.org/ns/1.0">

after this, in the Platform tag for android customize some lines check below
add usesCleartextTraffic=true after networkSecurityConfig and resource-file tags

 <platform name="android">
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:networkSecurityConfig="@xml/network_security_config" />
        </edit-config>
        <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
        <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
    </platform>

answered Jan 18, 2020 at 7:49

yash's user avatar

yashyash

2536 silver badges17 bronze badges

2

We are using the cordova-custom-config plugin to manage our Android configuration. In this case the solution was to add a new custom-preference to our config.xml:

    <platform name="android">

        <preference name="orientation" value="portrait" />

        <!-- ... other settings ... -->

        <!-- Allow http connections (by default Android only allows https) -->
        <!-- See: https://stackoverflow.com/questions/54752716/ -->
        <custom-preference
            name="android-manifest/application/@android:usesCleartextTraffic"
            value="true" />

    </platform>

Does anybody know how to do this only for development builds? I would be happy for release builds to leave this setting false.

(I see the iOS configuration offers buildType="debug" for that, but I’m not sure if this applies to Android configuration.)

answered Dec 12, 2019 at 7:30

joeytwiddle's user avatar

joeytwiddlejoeytwiddle

28.2k12 gold badges117 silver badges107 bronze badges

In an Ionic 4 capacitor project, when I packaged and deployed to android phone for testing I got this error. Resolved by re-installing capacitor and updating android platform.

npm run build --prod --release
npx cap copy
npm install --save @capacitor/core @capacitor/cli
npx cap init
npx cap update android
npx cap open android

answered Jan 22, 2020 at 20:48

Karthik Sankar's user avatar

If You have Legacy Cordova framework having issues with NPM and Cordova command. I would suggest the below option.

Create file android/res/xml/network_security_config.xml —

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    <base-config cleartextTrafficPermitted="true" />
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
    </domain-config>
    </network-security-config>

AndroidManifest.xml —

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
        <uses-permission android:name="android.permission.INTERNET" />
        <application
            ...
            android:networkSecurityConfig="@xml/network_security_config"
            ...>
            ...
        </application>
    </manifest>

answered Jan 22, 2020 at 22:16

Pradeepta's user avatar

PradeeptaPradeepta

2382 silver badges2 bronze badges

3

Android WebView is a system component powered by Chrome that allows Android apps to display web content. In other words, WebView is an embeddable browser that a native application can use to display web content.

One of the most common uses for a WebView is to display the contents of a link inside an app without leaving it. In recent Android versions, you might sometimes see ERR_CLEARTEXT_NOT_PERMITTED error if you try to open an unsecured URL (usually a HTTP URL).

Below is a screenshot of the error.

ERR_CLEARTEXT_NOT_PERMITTED in the wild

The very same unsecured URLs can be opened in Chrome, Edge or any dedicated browser just fine, which could cause confusion across new developers.

This article will explain why ERR_CLEARTEXT_NOT_PERMITTED happens, and what you can do to fix it.

Why does ERR_CLEARTEXT_NOT_PERMITTED happens?

Cleartext is any transmitted or stored information that is not encrypted or meant to be encrypted.
Anything that is transferred in unsecured URL can be categorized as cleartext information. Those information can be eavesdropped or tampered by a malicious third party. In rare cases, they can launch an attack directed towards your device or leaking your personal information.

Starting from Android 9.0 (API level 28), Google has decided to phase out support for cleartext network protocols in the WebView. Any attempt to access a non-HTTPS URL will raise ERR_CLEARTEXT_NOT_PERMITTED error.

The proper solution for this error is to simply use HTTPS URLs for all of your endpoints and remove all unsecured URLs from your codebase.

Workaround to avoid ERR_CLEARTEXT_NOT_PERMITTED

If you don’t have access to the infrastructure to force every connection to use HTTPS, you can try the adding the flag android:usesCleartextTraffic="true" into AndroidManifest.xml.

First you need to edit the Android Manifest file at android/app/src/main/AndroidManifest.xml and add the following line into the application tag.

android:usesCleartextTraffic="true"

Code language: JavaScript (javascript)

The file after the changes would look something like this :
BEFORE

<application android:name="io.flutter.app.Test" android:label="bell_ui" android:icon="@mapmap/ic_launcher">

Code language: HTML, XML (xml)

AFTER

<application android:name="io.flutter.app.Test" android:label="bell_ui" android:icon="@mapmap/ic_launcher" android:usesCleartextTraffic="true">

Code language: HTML, XML (xml)

The workaround might be good for testing and debugging. However, it leaves a big security hole and opens a threat to data integrity.

Android 7+ ERR_CLEARTEXT_NOT_PERMITTED solution

Another better solution introduced from Android 7.0 is to configure the network_security_config.xml file. You can read more about it in Google’s Network security configuration page.

Basically, network_security_config.xml allows you to whitelist a domain from the global security rules. Therefore, the traffic comes to and from that domain would not be raise ERR_CLEARTEXT_NOT_PERMITTED.

First, you need to create a file in res/xml/ and name it network_security_config.xml.

edit network_security_config.xml to fix ERR_CLEARTEXT_NOT_PERMITTED

Then you need to add a domain configuration block and set cleartextTrafficPermitted flag to true so it would look like this.

<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">your_domain.com</domain> </domain-config> </network-security-config>

Code language: HTML, XML (xml)

After that, you need to spcify the path to your network security config file under your AndroidManifest so it would look like below :

<application android:name=".DemoApp" android:networkSecurityConfig="@xml/network_security_config" ...

Code language: HTML, XML (xml)

We hope that the solutions above help you solve your problem. Please note that the proper way to fix the error is using a secure network traffic protocol rather than a cleartext one.

We’ve also written a few other guides on fixing common Chrome error messages, such as How to fix ERR_SSL_PROTOCOL_ERROR and ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION that you may want to check out.

Opening URL inside any Android Application will use Android Webview and for some URLs, you might encounter ERR_CLEARTEXT_NOT_PERMITTED Error. The error should look similar to the below image.
fix err_cleartext_not_permitted error

So what this exactly mean?

Cleartext is any transmitted or stored information that is not encrypted or meant to be encrypted. When an app communicates with servers using a cleartext network traffic, such as HTTP, it could raise the risk of eavesdropping and tampering of content. Third parties can inject unauthorized data or leak information about the users. That is why developers are encouraged to secure traffic only, such as HTTPS. Starting with Android 9.0 (API level 28), cleartext support is disabled by default. Due to security purposes URL without HTTPS will throw err_cleartext_not_permitted error whenever an application uses it in the Android webview.

There’s an easy solution to fix err_cleartext_not_permitted error and i.e. don’t use insecure URLs. It is recommended to force HTTPs on your websites and remove all the insecure URLs i.e. non-HTTPs from the application. You will find the following guides helpful in forcing HTTPs on your websites.

Force HTTPS for WordPress websites by .htaccess 

Force HTTPS on the HTML/PHP Websites using .htaccess

We hope the above guides help you to fix err_cleartext_not_permitted error for the insecure URLs.

Android Application Code Fix

If you are an application developer and facing the issue then this can be fixed by adding android:usesCleartextTraffic="true" flag in the AndroidManifest.xml file under the application block.

Open the android manifest file (android/app/src/main/AndroidManifest.xml) and add the following into the application tag.

android:usesCleartextTraffic="true"

Find an example below to add the flag correctly.

Before Code

<application
        android:name="io.flutter.app.Test"
        android:label="ginger_ui"
        android:icon="@mipmap/ic_launcher">

After Code (changes/addition in bold)

<application
        android:name="io.flutter.app.Test"
        android:label="ginger_ui"
        android:icon="@mipmap/ic_launcher"
       android:usesCleartextTraffic="true">

Adding the above flag will start accepting the non-HTTPs Traffic in the app and fix err:ERR_CLEARTEXT_NOT_PERMITTED error.  But still at the end of the day, better to use secure network traffic rather than cleartext.

Feel free to reach us out if you need kind of assistance with any technical queries. Shoot us an email at technical@basezap.com, and our professional experts will get in touch with you.

In main directory of your Flutter project you have three main folders:

- lib         =  your Dart code
- ios         =  generated structure for iOS platform
- android     =  generated structure for Android platform

We are interested in android directory.
When you open it, you will see «typical Android app structure».

So you have to do 2 things:

1) Add new file in res

Go to directory:

my_flutter_project/android/app/src/main/res/

Create xml directory (in res!)

And inside xml add new file with name: network_security_config.xml and content:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

network_security_config.xml should be located in path:

my_flutter_project/android/app/src/main/res/xml/network_security_config.xml

network_security_config

Here you can find more information about this file:

https://developer.android.com/training/articles/security-config

2) Modify AndroidManifest.xml

Go to:

flutter_project/android/app/src/main/AndroidManifest.xml

enter image description here

AndroidManifest.xml is XML file, with structure:

<manifest>
    <application>
        <activity>
            ...
        </activity>
        <meta-data >
    </application>
</manifest>

So for <application> PROPERTIES you have to add 1 line:

android:networkSecurityConfig="@xml/network_security_config"

enter image description here

Remember that you have to add it as property (inside application opening tag):

<application

    SOMEWHERE HERE IS OK

>

Not as a tag:

<application>           <--- opening tag

    HERE IS WRONG!!!!

<application/>          <--- closing tag

In main directory of your Flutter project you have three main folders:

- lib         =  your Dart code
- ios         =  generated structure for iOS platform
- android     =  generated structure for Android platform

We are interested in android directory.
When you open it, you will see «typical Android app structure».

So you have to do 2 things:

1) Add new file in res

Go to directory:

my_flutter_project/android/app/src/main/res/

Create xml directory (in res!)

And inside xml add new file with name: network_security_config.xml and content:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

network_security_config.xml should be located in path:

my_flutter_project/android/app/src/main/res/xml/network_security_config.xml

network_security_config

Here you can find more information about this file:

https://developer.android.com/training/articles/security-config

2) Modify AndroidManifest.xml

Go to:

flutter_project/android/app/src/main/AndroidManifest.xml

enter image description here

AndroidManifest.xml is XML file, with structure:

<manifest>
    <application>
        <activity>
            ...
        </activity>
        <meta-data >
    </application>
</manifest>

So for <application> PROPERTIES you have to add 1 line:

android:networkSecurityConfig="@xml/network_security_config"

enter image description here

Remember that you have to add it as property (inside application opening tag):

<application

    SOMEWHERE HERE IS OK

>

Not as a tag:

<application>           <--- opening tag

    HERE IS WRONG!!!!

<application/>          <--- closing tag


Net::err_cleartext_not_permitted | How to fix net err cleartext not permitted

Видео: Net::err_cleartext_not_permitted | How to fix net err cleartext not permitted

Содержание

  • Что означает net :: err_cleartext_not_permitted?
  • Почему эта ошибка повторяется
  • Как исправить net :: err_cleartext_not_permitted?
  • Facebook:
  • net :: err_cleartext_not_permitted в Facebook:
  • Facebook Посланник
  • Хакеры
  • заблокировать любой несанкционированный доступ
  • Резюме:
  • Похожие сообщения:

Мобильный телефон стал необходимостью в нашей повседневной жизни. В наши дни вся наша работа, будь то личная или профессиональная, выполняется с помощью мобильных телефонов. От серфинга в Интернете, разговоров с друзьями, семьей и коллегами до обмена важными документами с ними, мобильные телефоны и Интернет стали неотъемлемой частью нашей жизни. Интернет — одна из таких интересных вещей, которая позволяет любым двум людям подключиться за секунды. Когда мы используем веб-браузеры, мы часто сталкиваемся с некоторыми ошибками, например Net :: err_cleartext_not_permitted. Это может быть техническая ошибка на сайте сервера или ошибка из-за нашей низкой пропускной способности.

Но часто ли мы обращаем внимание на эти сообщения об ошибках? Что они могут значить? Или почему они возникают? Такие мысли редко приходят нам в голову. Мы просто сосредотачиваемся на исправлении ошибок и работе над своими делами. Мы никогда не пытаемся понять значение этих сообщений об ошибках или какое сообщение они пытаются нам передать. Одно из таких сообщений об ошибке:net :: err_cleartext_not_permitted.

Не пропусти: NET :: ERR_CERT_WEAK_SIGNATURE_ALGORITHM

Что означает net :: err_cleartext_not_permitted?

Мы открываем так много URL-адресов в нашем браузере. В приложении для Android Android WebView используется для открытия этих URL. Это системный компонент для отображения содержимого в Интернете, работающий под управлением Chrome. WebView используется для отображения содержимого в Интернете собственного приложения из встроенного браузера. Мы можем использовать WebView для просмотра содержимого ссылки внутри любого приложения. Также нам не нужно выходить из заявки. Кроме того, мы можем видеть его содержимое внутри приложения. При открытии URL-адресов мы иногда получаем сообщение об ошибке «net :: err_cleartext_not_permitted ». Итак, что это значит?

Любая информация, которая передается или хранится без шифрования, называется открытым текстом. Это информация, передаваемая по небезопасному URL-адресу. Сетевой трафик Cleartext вызывает опасения по поводу подслушивания и подделки контента, когда приложения используют его для связи с серверами какой-либо третьей стороной. Пользовательские данные и информация могут быть пропущены ими путем введения каких-либо неавторизованных данных. Открытый текст обычно использует URL-адрес HTTP, который не является безопасным, поэтому при использовании HTTP существуют факторы риска. Https — более безопасный вариант для безопасного трафика. От Android 9, функция открытого текста по умолчанию отключена. Любое приложение, использующее Android WebView для открытия URL-адресов без HTTPS, выдаст ошибку как — «net :: err_cleartext_not_permitted».

Почему эта ошибка повторяется

Мы знаем значениеnet :: err_cleartext_not_permittedошибкаТеперь дайте нам знать Почему эта ошибка повторяется. Причина этой ошибки заключается в том, что на вашем устройстве отключена поддержка открытого текста из соображений безопасности. Итак, когда мы пытаемся открыть веб-сайт с URL-адресом HTTP в Android WebView, эта ошибка возникает, чтобы вы знали, что WebView не может получить доступ к этому веб-сайту по соображениям безопасности. Веб-сайт, который вы пытаетесь открыть, может быть подвержен атакам и может быть легко взломан, поэтому эта ошибка не позволяет вам получить доступ к этому небезопасному веб-сайту.

Как исправить net :: err_cleartext_not_permitted?

Самый удобный и простой способ исправить «net :: err_cleartext_not_permitted”Ошибка заключается в использовании URL-адресов с HTTPS. Мы не должны использовать небезопасные URL-адреса и использовать веб-сайт с URL-адресом HTTPS. Мы должны удалить все небезопасные URL-адреса без HTTPS из наших приложений. Разработчики могут принудительно использовать HTTPS для веб-сайтов, но у них должен быть действующий сертификат SSL для своего домена. Есть несколько способов сделать это:

  • Мы должны войти в протокол передачи файлов или cPanel.
  • Зайдите в Файловый менеджер.
  • В корневом каталоге сгенерируйте .htaccess.
  • Запишите коды в файл .htaccess. Сохраните файл.
  • Необходимо отредактировать конфигурационный файл PHP. Сайт и базовый URL должны быть обновлены.

Любой разработчик приложений, столкнувшийся с проблемой «net :: err_cleartext_not_permitted», может исправить это, добавив некоторый код в AndroidManifest.xml файл. Кодandroid: usesCleartextTraffic = «true». Разработчик должен добавить этот код в файл AndroidManifest.xml. После добавления кода флаг начинает принимать не-HTTPS-трафик, и ошибка исправляется.

Facebook:

Facebook стал очень популярной и крупнейшей социальной сетью. Люди со всего мира могут подключаться через Facebook. Facebook помогает людям общаться и получает доход от рекламы. Пользователи Facebook должны создать учетную запись, используя действующий адрес электронной почты или номер телефона, за которым следует пароль. Пользователи могут писать о своих личных чувствах, добавлять фотографии или видео и общаться с людьми со всего мира. Люди настолько увлечены Facebook, что публикуют на нем любую информацию о себе. Они нажимают на все, что появляется в их лентах. Они ищут людей и устанавливают связи с незнакомцами на этой платформе. Facebook стал неотъемлемой частью социальных сетей.

net :: err_cleartext_not_permitted в Facebook:

Но иногда, когда мы нажимаем на любую статью или ссылку в ленте новостей Facebook, мы получаем сообщение об ошибке:net :: err_cleartext_not_permitted.Эта ошибка означает, что приложение не позволяет открывать статьи или ссылки с URL-адресом HTTP. Указанная статья или ссылка могут соединить вас с небезопасным веб-сайтом, который может быть подвержен хакерским атакам или любой другой проблеме безопасности. Эта функция была крупным обновлением на Facebook. Было много инцидентов, когда хакеры атаковали и взламывали учетные записи пользователей, использующих эти ссылки в статьях. Опасность в сети теперь уже не для шуток. Люди теряют свои кровно заработанные деньги и репутацию, совершая глупые ошибки в Интернете. Эти обновления сделаны для того, чтобы люди были осведомлены о вредоносных действиях, которые могут происходить через ссылки на небезопасные веб-сайты, и быть осторожными.

Facebook Посланник

Facebook Messenger, приложение для обмена сообщениями, созданное Facebook, теперь тоже подвержено хакерским атакам. Приложение было создано как платформа для обмена мгновенными сообщениями. Уязвимость в этом приложении заключается в том, что любой пользователь, который посещает веб-сайт по незащищенным ссылкам из Messenger, все еще находясь в Facebook, может передать свою личную информацию злоумышленникам. Информация может включать имя, адрес электронной почты, контакт, образование, место проживания, интересы и увлечения пользователя. Сообщения в Messenger не зашифрованы сквозным шифрованием, что делает его более уязвимым.

Хакеры

Хакеры могут легко получить доступ к вашему мессенджеру и узнать людей, с которыми вы общаетесь и обмениваетесь сообщениями. Кроме того, хакеры используют эту платформу для распространения небезопасных ссылок. Эти ссылки могут превратиться в огромную киберугрозу при нажатии на них. Хакеры отправляют фиктивные сообщения с текстом, видео или аудио, прикрепленными со ссылкой. При нажатии на эти ссылки пользователи переходят на вредоносные веб-сайты в их браузерах. Хакеры могут даже заразить устройство пользователя.

Если устройство пользователя взломано, хакеры используют его для отправки вредоносных ссылок контактам этого пользователя. Цикл продолжается, и все больше устройств начинают заражаться по цепной реакции. Если атака более серьезна, хакер может отслеживать активность клавиатуры на устройстве, что может раскрыть банковские реквизиты пользователя, если он регулярно использует банковские приложения. Хакер может легко использовать детали и может нанести больший вред пользователю.

В некоторых случаях ссылки, которые открывают видео YouTube, отправляются пользователям в Messenger. Эти ссылки также доступны в виде рекламы в ленте новостей пользователей. Кажется, что когда вы перейдете по этой ссылке, вы сможете посмотреть видео на YouTube. Когда вы открываете ссылку, она переводит вас не на какое-либо видео, а на поддельную страницу входа в Facebook. Многие пользователи не находят ничего плохого в этих ссылках и сразу же входят в систему со своими учетными данными. Пользователи не могут отличить настоящую страницу от поддельной и в конечном итоге предоставляют свои учетные данные.

заблокировать любой несанкционированный доступ

Злоумышленники могут легко использовать свои учетные данные и взломать свои учетные записи. Они могут использовать взломанную учетную запись для выполнения любых вредоносных действий. Он может пересылать ссылку людям из вашего списка друзей.Мы всегда должны проявлять осторожность при переходе по любым ссылкам в Facebook. Кроме того, мы не должны переходить по какой-либо ссылке, которая может быть подозрительной.

Здесьnet :: err_cleartext_not_permittedприходит поиграть. Поскольку открытый текст по умолчанию отключен на большинстве устройств с версией Android 9 и выше, любая ссылка с незашифрованной информацией не открывается, и пользователям отображается сообщение об ошибке. Это важный шаг для сохранения информации о пользователе и блокировки любого несанкционированного доступа к устройству пользователя по любым ссылкам. Узнать больше о com.facebook.orca & com.facebook.katana.

Резюме:

В Facebook есть даже ссылки, которые, кажется, открывают видео на YouTube, но перенаправляют вас на поддельную страницу входа в Facebook. Злоумышленники могут получить от него учетные данные пользователя и выполнить злонамеренные действия с учетной записью пользователя. net :: err_cleartext_not_permittedОшибка не позволяет пользователям открывать небезопасный веб-сайт с помощью URL-адреса HTTP. Таким образом, пользователи защищены от любых злонамеренных действий, совершаемых с небезопасных ссылок и веб-сайтов.

Похожие сообщения:

  • Как изменить имя устройства android

Learn how to prevent the net::ERR_CLEARTEXT_NOT_PERMITTED error from appearing in your Cordova application.

After 2 years of working with different technologies, I started using Cordova once again for a tiny side project. As usual with everything I work with, when trying something quite simple, there errors of any kind, this time the error seemed to be related to the network configuration.

Cause of this issue

This problem will always be triggered in your project if you haven’t enabled the cleartext support i nyour application. In my case with the Cordova In App Browser, the following code triggers the exception:

let ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');

The apache website works normally in my browser, so what’s the real problem? In this case, when you trigger a request to http://apache.org, the server will make a redirect because the https connection is missing as well as the www that is forced when you create the request. Your application blocks the first redirect as it has been done through HTTP (insecure). If you trigger the request using https, then it works perfectly:

let ref = cordova.InAppBrowser.open('https://apache.org', '_blank', 'location=yes');

Thats the reason of this problem. Clear Text traffic is basically text that has not been subjected to encryption and is not meant to be encrypted.

Possible solution #1

The most obvious solution is to simply add the correct protocol to the website that you’re trying to open (HTTPS) as long as the server from which the information is requested supports said protocol.

Possible solution #2

The first solution isn’t that useful when you are working with websites that don’t offer a secure connection or with local files.

As mentioned, the cleartext traffic support is disabled by default Starting with Android 9 (API level 28), so you can enable it if you need to. Simply add the following attribute to the application node in your AndroidManifest.xml file:

android:usesCleartextTraffic="true"

Your file will look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourcompany.packagename">

    <application
        ...
        android:usesCleartextTraffic="true"
        ...
        >

This will allow the clear text traffic from any source which depending on your needs may be the best solution. Try building your application and launch the In App Browser with the URL that was throwing the exception and it should work now.

Possible solution #3

Alternatively if you need to allow the clear text traffic from certain sources only, you may specify it using the network security configuration file of your android application (res/xml/network_security_config.xml):

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain 
            includeSubdomains="true"
            cleartextTrafficPermitted="true"
        >example.com</domain>
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>

Change the example.com domain with the one you need and be sure to use the mentioned configuration file in your AndroidManifest.xml file like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourcompany.packagename">

    <application
        android:networkSecurityConfig="@xml/network_security_config"
        >

Happy coding ❤️!

Outline of Article Content
1. Error OverView: android webview showing net::ERR_CLEARTEXT_NOT_PERMITTED
2. Fix Cleartext Traffic Error in Android 9 Pie
2.1. Network security configuration to allow all Network connection types HTTP and HTTPS in Android (9) Pie
2.2. While allowing clear traffic to all domains by using above point: Google Play release APK will face Security -> 1 known vulnerability detected in APK 51
2.3. Network security configuration allows an app to permit cleartext traffic from a certain domains.
3. Gain More Understanding on Domain and Sub-Domain

1. Android Webview showing net::ERR_CLEARTEXT_NOT_PERMITTED:

err cleartext not permitted android 9 Pie (API level 28) Webview
android 9 webview showing net::ERR_CLEARTEXT_NOT_PERMITTED

Webpage not available
The webpage at http://geekscompete.blogspot.com/2019/04/ugc-net-cs-2018-julpii-question-87.html could not be loaded because:
net::ERR_CLEARTEXT_NOT_PERMITTED

2. How to Fix net::err_cleartext_not_permitted Error in Android 9 Pie Webview

2.1 To allow all Network connection types HTTP and HTTPS in Android (9) Pie:

Need to follow the below two steps to Fix Cleartext Traffic Error in Android 9 Pie:

1) You now have to create a new file in your xml folder, file named network_security_config just like the way you have named it in the AndroidManifest.xml .
2) You have to set  android:networkSecurityConfig=»@xml/network_security_config» in the application tag of your AndroidManifest.xml. This deceleration in your android application will allow cleartext traffic to all Network connection types in Android 9 Pie.

Step 1. Create a new file res/xml/network_security_config.xml and the content of your file should be like this to enable all webview URL requests without encryptions:

Code for network_security_config.xml:

<?xml version=»1.0″ encoding=»utf-8″?>
<network-security-config>
    <base-config cleartextTrafficPermitted=»true»>
        <trust-anchors>
            <certificates src=»system» />
        </trust-anchors>
    </base-config>
</network-security-config>

Step 2. Add network security config created above to your Android manifest file under application tag.

Code for AndroidManifest.xml:

<?xml version=»1.0″ encoding=»utf-8″?>
<manifest xmlns:android=»http://schemas.android.com/apk/res/android»
          package=»com.yourappname»>
    <uses-permission android:name=»android.permission.INTERNET» />

 
    <application
        android:name=».MainApplication»
        android:icon=»@mipmap/ic_launcher»
        android:label=»@string/app_name»
        android:largeHeap=»true»
        android:allowBackup=»false»
        android:supportsRtl=»true»
        android:networkSecurityConfig=»@xml/network_security_config»
        android:theme=»@style/AppTheme»>
    </application>
</manifest>

2.2 Security -> 1 known vulnerability detected in APK 51

You may also face warning messag as below on Google Play Console for your released APK/s If you have allowed clear text traffic for all network traffic as suggested in step 2.1 of this article.
Cleartext traffic allowed for all domains
Detected in APK 48, 49, 50, 51
Your app’s Network Security Configuration allows cleartext traffic for all domains. This could allow eavesdroppers to intercept data sent by your app. If that data is sensitive or user-identifiable it could impact the privacy of your users.

Consider only permitting encrypted traffic by setting the cleartextTrafficPermitted flag to false, or adding an encrypted policy for specific domains. Learn more

2.3 Network security configuration — allows an app to permit cleartext traffic to/from a specific domain/s

If you have some limited number of specific domains for which you want to allow clear traffic then use below content for your res/xml/network_security_config.xml file with your  domain/s specified:
Code for network_security_config.xml:

<?xml version=»1.0″ encoding=»utf-8″?>
<network-security-config>
    <domain-config cleartextTrafficPermitted=»true»>
        <domain includeSubdomains=»true»>geekscompete.com</domain>
        <domain includeSubdomains=»true»>geekscompete.blogspot.com</domain>
    </domain-config>
</network-security-config>

Understanding on domain and subdomain:

Lets say your main domain is as below:
geekscompete.com

For example, you could create a subdomain for gallery pictures on your site called «gallery» that is accessible through the URL gallery.geekscompete.com in addition to www.geekscompete.com/gallery.
You can also set even more specific area of interest on your sitepage for your site with new subdoamin like below:
info.blog.geekscompete.com

Example of subdomain for the above domain are:
www.geekscompete.com
blog.geekscompete.com
info.blog.geekscompete.com
gallery.geekscompete.com

See here, The structure and components of a URL to better understand the concept of the subdomain



More about Network security configuration:

<network-security-config>
can contain below tags:
0 or 1 of <base-config>
Any number of <domain-config>
0 or 1 of <debug-overrides>

Here these tags are:
<base-config> is the default configuration set for all network connections whose destination is not covered by a <domain-config>.
<domain-config> is configuration to be used for network connections to specified destinations, as defined by the domain elements.

Any values that are not set in <base-config> will use the platform default values.

The default configuration for applications which targets Android 9 Pie (API level 28) and higher is as follows:

<base-config cleartextTrafficPermitted=»false»>
    <trust-anchors>
        <certificates src=»system» />
    </trust-anchors>
</base-config>

The default configuration for applications which targets Android 7.0 Nougat (API level 24) to Android 8.1 Oreo (API level 27) is as follows:

<base-config cleartextTrafficPermitted=»true»>
    <trust-anchors>
        <certificates src=»system» />
    </trust-anchors>
</base-config>

The default configuration for applications which targets Android 6.0 Marshmallow (API level 23) and lower is as follows:

<base-config cleartextTrafficPermitted=»true»>
    <trust-anchors>
        <certificates src=»system» />
        <certificates src=»user» />
    </trust-anchors>
</base-config>

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка net err cert common name invalid
  • Ошибка net err cert authority invalid как исправить