Android 8: Cleartext HTTP traffic not permitted
Asked Answered
O

38

1715

I had reports from users with Android 8 that my app (that uses back-end feed) does not show content. After investigation I found following Exception happening on Android 8:

08-29 12:03:11.246 11285-11285/ E/: [12:03:11.245, main]: Exception: IOException java.io.IOException: Cleartext HTTP traffic to * not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:115)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:458)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.doConnection(AbstractHttpAsyncTask.java:207)
at com.deiw.android.generic.tasks.AbstractHttpAsyncTask.extendedDoInBackground(AbstractHttpAsyncTask.java:102)
at com.deiw.android.generic.tasks.AbstractAsyncTask.doInBackground(AbstractAsyncTask.java:88)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

(I've removed package name, URL and other possible identifiers)

On Android 7 and lower everything works, I do not set android:usesCleartextTraffic in Manifest (and setting it to true does not help, that is the default value anyway), neither do I use Network Security Information. If I call NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(), it returns false for Android 8, true for older version, using the same apk file. I tried to find some mention of this on Google info about Android O, but without success.

Obregon answered 29/8, 2017 at 13:48 Comment(4)
This happens on an app I maintain because the server redirects from HTTPS to HTTP in some instances.Freehearted
check here codechacha.com/en/android-cleartext-http-traffic-issueCymograph
I am building for API level 30, Android 11, and adding android:usesCleartextTraffic="true" in application tag in manifest worksScraper
Reported elsewhere as not happening until Android 9. This is news for me.Normalie
B
3365

According to Network security configuration -

Starting with Android 9 (API level 28), cleartext support is disabled by default.

Also have a look at Android M and the war on cleartext traffic

Codelabs explanation from Google

Option 1 -

First try hitting the URL with https:// instead of http://

Option 2 -

Create file res/xml/network_security_config.xml -

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

Option 3 -

android:usesCleartextTraffic Doc

AndroidManifest.xml -

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

Also as @david.s' answer pointed out android:targetSandboxVersion can be a problem too -

According to Manifest Docs -

android:targetSandboxVersion

The target sandbox for this app to use. The higher the sandbox version number, the higher the level of security. Its default value is 1; you can also set it to 2. Setting this attribute to 2 switches the app to a different SELinux sandbox. The following restrictions apply to a level 2 sandbox:

  • The default value of usesCleartextTraffic in the Network Security Config is false.
  • Uid sharing is not permitted.

So Option 4 -

If you have android:targetSandboxVersion in <manifest> then reduce it to 1

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest android:targetSandboxVersion="1">
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>
Bona answered 13/6, 2018 at 10:11 Comment(29)
@HrishikeshKadam your answer is much appreciated but it seems there must be another step in the most recent release of P? Please see my question #51770823Heartily
Could somebody tell me how to apply versions specified in this answer to debug build type only?Chill
But what if this happens? I can't set my minSdkversion to 23..Adulterate
Does ClearText HTTP mean that they were just using a http site instead of https?Filibeg
@Chill you don't need to set your minimum to 23 to use the attributes in the manifest that are introduced later. Earlier versions will ignore them. And you can suppress the warning with tools:ignore="UnusedAttribute">Supervene
Why does op have cleartext issue if he's on android 8 though? It's disabled by default only in android 9.Karelia
What's the point of this Android security feature if every developer going to add android:usesCleartextTraffic="true" ?Huskamp
This does not even mention the best solution to this problem: Use HTTPS. The options mentioned in this answer should only be a last resort.Corporate
Option one was the only option that really worked for us. Option 2 would work intermittently but wasn't consistent. We needed this for dev environments but production we needed ssl.Sarawak
@林果皞 it'll be easy for google play store to eventually just ban apps that use this flagDiscontinue
If you need this for your development environment, please use a manifest placeholder for it (see: #37471350 ). For your production environment, please use HTTPS.Valetudinarian
Can someone help me to bypass the https check for WebViews,my WebViews contain so many redirection urls and these urls are unknown to the app (not subdomain). I don't want to bypass these checks for all the urlsPalmapalmaceous
I had to also add 10.0.2.2 as a proxy in the (Google) emulator for this (Option 1) to work.Haemostat
Everything have a other solutions, So Why its added in 28 ? @HrishikeshKadamCogon
Trying to get 'Sunshine' tutorial app on Udacity to work. Option 2 gives me: AAPT: error: attribute android:usesCleartextTraffic not found.Haught
@林果皞 What's the alternate of it with security too working?Aseity
It worked for me, but with it I also had to upgrade the OkHttp version to latest (4.1.1).....Lavonlavona
Does Option 2 is safe?Invincible
As @ChristianBrüggemann says, use HTTPS. You can probably do this just by changing your URL from http://... to https://...Stringency
@ZeeshanAyaz what i need to mention in here : <domain includeSubdomains="true">api.example.com(to be adjusted)</domain>Workmanlike
@Sarawak You've mentioned that Option 2 worked intermittently for you. Could it be that you've used lower API version than API 23? Because android:usesCleartextTraffic is supported from API 23Kingdon
@HrishikeshKadam I am working in aosp. Where exactly cleartext support is disabled by default? Because if I change in top of the aosp class, I can make all other apps to work. Because I can't change all 1000's of apps developed in 6 to permit this. So where exactly or which class in aosp, I can change this?Halmstad
Also you need to set network_security_config.xml's build action to AndroidResource. Otherwise, you will get a compile error "resource xml/network_security_config (aka com.companyname.sample:xml/network_security_config) not found."Considering
You can set it to only use cleartext traffic in debug builds. See here: https://mcmap.net/q/35675/-android-8-cleartext-http-traffic-not-permittedPetras
I actually needed to connect integration tests to my local http server running in the other service, sure, you shouldn't use that in production or app code.Erechtheus
Option 2 would have been perfect, but I have to support API 19, which doesn't support it. Even option 3 required API 23 at minimum. So what should we do?Cerebritis
@HrishikeshKadam:sir i tried 2nd option but after build android all my changes are replaced can you tell me why?Mesquite
Use sslshopper.com/ssl-checker.html to see if there's something wrong with the SSL certs on the server. If the chain of certs is broken, android won't let https requests go through. See my full answer below. You may have different problems.Corrianne
My backend server was automatically doing HTTPS redirection, so first I had to turn that off. Then I used option 2 to allow clearText on 10.0.2.2. Works great!Aguilar
T
261

My problem in Android 9 was navigating on a webview over domains with http The solution from this answer

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

and:

res/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>
</network-security-config>
Terbia answered 19/1, 2019 at 15:32 Comment(5)
Can I somehow rewrite this in gradle?Steelmaker
Not working for me. I can't get my emulator to connect to 10.0.2.2Way
Thi is not the "safest" thing to do on release builds.Tibiotarsus
How if I wan to put port number together?Inchmeal
This is not recommended. Network security configuration codelabCooks
O
185

In the AndroidManifest I found this parameter:

android:networkSecurityConfig="@xml/network_security_config"

and @xml/network_security_config is defined in network_security_config.xml as:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <!--Set application-wide security config using base-config tag.-->
    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

just I changed cleartextTrafficPermitted to true

Ornithosis answered 21/3, 2018 at 4:10 Comment(4)
Perfetct. More information here: codelabs.developers.google.com/codelabs/…Buddhology
Reinstall the app after the changesWay
The only answer it worked for me (I had to create the file and add the parameter).Studious
Not good practise to disable ssl requirements unless this was for internal app of course. But even then should never be disabled.Licketysplit
P
152

You might only want to allow cleartext while debugging, but keep the security benefits of rejecting cleartext in production. This is useful for me because I test my app against a development server that does not support https. Here is how to enforce https in production, but allow cleartext in debug mode:

In build.gradle:

// Put this in your buildtypes debug section:
manifestPlaceholders = [usesCleartextTraffic:"true"]

// Put this in your buildtypes release section
manifestPlaceholders = [usesCleartextTraffic:"false"]

In the application tag in AndroidManifest.xml

android:usesCleartextTraffic="${usesCleartextTraffic}"
Petras answered 11/12, 2018 at 21:47 Comment(2)
it's only used on api 23+ though. If you want an api independent solution the approved one at: #46302558 is a good option...Cantatrice
Question: when the app uses web servers that can be http or https by design, will usesCleartextTraffic:"false" even matter if the http urls need to be able to use the web services? So setting it to true means the https services by default don't send clear text anyway?Cathrin
T
72

Ok, that's ⇒⇒ NOT ⇐⇐ the thousands repeat of add it to your Manifest, but an hint which based on this, but give you additional Benefit (and maybe some Background Info).


Following solution allow you to set the protocol (HTTP / HTTPS) per ENVIRONMENT.

This way you are able to use http for your DEV-Environment, and https for your PRODUCTION-Environment, without the need to change it all the time! And this is needed, because generally you don't have an https-certificate for your local or dev environment, but it's a MUST-HAVE for production (and maybe for staging) environments.


Android has a kind of overwriting functionality for the src-Directory.

By default, you have

/app/src/main

But you can add additional directories to overwrite your AndroidManifest.xml. Here is how it works:

  • Create the Directory /app/src/debug
  • Inside create the AndroidManifest.xml

Inside of this File, you don't have to put all the Rules inside, but only the ones you like to overwrite from your /app/src/main/AndroidManifest.xml

Here an Example how it looks like for the requested CLEARTEXT-Permission:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.yourappname">

    <application
            android:usesCleartextTraffic="true"
            android:name=".MainApplication"
            android:label="@string/app_name"
            android:icon="@mipmap/ic_launcher"
            android:allowBackup="false"
            android:theme="@style/AppTheme">
    </application>

</manifest>

With this knowledge it's now easy as 1,2,3 for you to overload your Permissions depending on your debug | main | release Enviroment.

The big benefit on it... you don't have debug-stuff in your production-Manifest and you keep an straight and easy maintainable structure

Track answered 24/1, 2019 at 21:2 Comment(2)
This is definitely the proper solution. Android has added these security settings for a reason, so they should stand. Your solutions allows us to test on local insecure environments, while the production builds will still have the recommended security settings. Thank you!Centonze
Certainly in prod the last leg is almost always cleartext in any case. One would think that in developer mode we could override this with a toggle.Normalie
S
59

If possible change your url's from HTTP to HTTPS;

It works out!!!

Stila answered 4/10, 2018 at 17:12 Comment(13)
how is this upvoted? you'll get a handshake exception if your server url isn't httpsDiscontinue
upvoted because it's the right thing to do (in production environments). HTTPS should be the default, not HTTP.Valetudinarian
@beetsta You assume that you have full control over what is serving the content. This answer is therefore naive or flippant in nature.Phthalein
@Valetudinarian Why should be HTTPS default on a LOCAL machine while debugging? This is so stupid, just another example of Google paternalism. Luckily one can workaround this for debug mode by Tyler's solution.Wardieu
@MartinPrice, I agree the answer is too short and not applicable to all situations. However, neither are most of the other answers, in assuming that allowing HTTP traffic is the right way to go. Allowing cleartext traffic in all situations for all hosts totally ignores the reasons why Google changed this in the first place. For production environments HTTPS is nearly always the right way to go. Allowing HTTP in debug environments is of course not an issue, as I mentioned in the comment.Valetudinarian
The answer is ignorant of the question. Unlike people in small companies, sometime you don't have an SSL for every staging server. The answer is as bad as someone correcting grammar in a Facebook post and this doesn't answer the question at all, nor does it fix it.Lycaon
Nice if you are only connecting to a server you have control over. Any external websites that have links that use HTTP will still break. The correct general solution is the network security config file as given in other answers. Until the world completely moves to HTTPS, Google's security measure will just be a PIA requiring them to be effectively turned off.Colfin
I tried all other solutions but this was the right answer. I had to change my website(api) domain certificate to https. Then I changed my api url in the app and right now everything works like a charm! :)Serigraph
This answer is fine, simply because one can configure debug builds differently.Etienne
It says "if possible". This answer is correct. Exposing and consuming your services via HTTPS fixes the problem? Yes. Are there other options? Yes. Will this fit everyone in every stage? No.Settles
@NickTurner if you don't have certificate in your server it has nothing to do with the answer. The answer was not for security protocols violations, i'm sorry if you were looking for the one. ThanksStila
Actually it's still working fine with links having "http://", but not above Android 8 (API 27), so changing URL from "http://" to "https://" works on Android 11 API 30 and below all!Wharfage
This answer could not be applied to all cases, some staging sites don't have the https. But it works in some cases.Bloomers
T
54
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">***Your URL(ex: 127.0.0.1)***</domain>
    </domain-config>
</network-security-config>

In the suggestion provided above I was providing my URL as http://xyz.abc.com/mno/

I changed that to xyz.abc.com then it started working.

Tarsia answered 16/9, 2018 at 13:59 Comment(4)
Domain != URL. "http" is the protocol. The protocol is never part of the domain.Moser
This is correct, only FQDN are being supported there, no IP addresses (fixed that above).Etienne
Not working for domain 10.0.2.2. Should I add the port number?Way
How If I am using ip address instead of domain?Inchmeal
S
35

It could be useful for someone.

We recently had the same issue for Android 9, but we only needed to display some Urls within WebView, nothing very special. So adding android:usesCleartextTraffic="true" to Manifest worked, but we didn't want to compromise security of the whole app for this. So the fix was in changing links from http to https

Serilda answered 17/9, 2018 at 15:39 Comment(4)
If I only want to display some URLs I don't need a WebView. I just use a TextView. ;) I suppose you mean you show some html pages. Your fix only works if your server offers SSL. You can't simply change the links.Moser
This for sure is the best option whenever possible, but one can't always choose that - either for a performance reason or because simply the resource may not be available in cleartext HTTP.Trinitrocresol
"we didn't want to compromise security of the whole app", what security risks can it cause? In my case there is not one URL so i can't add them in manifest.Lenhart
Hi @RobertWilliams it just means that clear traffic would non encrypted traffic would be allowed. Here is a blogpost medium.com/@son.rommer/…Serilda
S
30

For React Native projects

It was already fixed on RN 0.59. You can find on upgrade diff from 0.58.6 to 0.59 You can apply it without upgrading you RN versionust follow the below steps:

Create files:

android/app/src/debug/res/xml/react_native_config.xml -

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
  </domain-config>
</network-security-config>

android/app/src/debug/AndroidManifest.xml -

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

  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

  <application tools:targetApi="28"
      tools:ignore="GoogleAppIndexingWarning" 
      android:networkSecurityConfig="@xml/react_native_config" />
</manifest>

Check the accepted answer to know the root cause.

Symbolist answered 13/3, 2019 at 16:51 Comment(2)
I use react-native 0.59.5 and i having the same problem, we have to setting manually the AndroidManifest.xml as you suggest.Racemic
Thank you It helped Due to google policy I have to made android:usesCleartextTraffic="false" then I had the problem of running react-native from local in the simulator I did apply the above steps and it worked for me.Broken
D
22

I have removed this line from the android manifest file which is already there

 android:networkSecurityConfig="@xml/network_security_config" 

and added

android:usesCleartextTraffic="true"

this in to application tag in manifest

<application
    android:usesCleartextTraffic="true"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    >

then this error Cleartext HTTP traffic to overlay.openstreetmap.nl not permitted is gone for me in android 9 and 10.I hope this will work for android 8 also if it is helped you don't forget to vote thank you

Desperate answered 27/1, 2020 at 16:31 Comment(2)
Saved my day. Many thanks 😊 ☺️Hu
Won't it effect to any existing functionality of app?Hu
V
17

Adding ... android:usesCleartextTraffic="true" ... to your manifest file may appear to fix the problem but it opens a threat to data integrity.

For security reasons I used manifest placeholders with android:usesCleartextTraffic inside the manifest file (like in Option 3 of the accepted answer i.e @Hrishikesh Kadam's response) to only allow cleartext on debug environment.

Inside my build.gradle(:app) file, I added a manifest placeholder like this:

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

        debug {
            manifestPlaceholders.cleartextTrafficPermitted ="true"
        }
    }

Note the placeholder name cleartextTrafficPermitted at this line above

            manifestPlaceholders.cleartextTrafficPermitted ="true"

Then in my Android Manifest, I used the same placeholder ...

AndroidManifest.xml -

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="${cleartextTrafficPermitted}"
        ...>
        ...
    </application>
</manifest>

With that, cleartext traffic is only permitted under the debug environment.

Vaporing answered 23/5, 2020 at 17:31 Comment(0)
T
17

Simple and Easiest Solution [Xamarin Form]

For Android

  1. Goto Android Project, then Click on Properties,

enter image description here

  1. Open AssemblyInfo.cs and paste this code right there:

    [assembly: Application(UsesCleartextTraffic =true)]

enter image description here

For iOS

Use NSAppTransportSecurity:

Enter image description here

You have to set the NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your info.plist file.

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

Plist configuration

Traweek answered 28/5, 2020 at 12:30 Comment(2)
this works like a charm, superb @Hemant RamphulBrandie
Absolutely superb!Rail
O
13

Okay, I have figured this out. It is due to the Manifest parameter android:targetSandboxVersion="2", that I have added because we also have Instant App version - it should make sure than once user upgrades from Instant App to regular app, he will not loose his data with the transfer. However as the vague description suggest:

Specifies the target sandbox this app wants to use. Higher sanbox versions will have increasing levels of security.

The default value of this attribute is 1.

It obviously also adds new level of security policy, at least on Android 8.

Obregon answered 30/8, 2017 at 8:15 Comment(0)
W
13

I would suggest to add both dev and prod network configs:

add res/xml/network_security_config_dev.xml

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

addres/xml/network_security_config_prod.xml

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

under Gradle Scripts (in android studio), find build.gradle (android.app) and look for buildTypes: release and debug (create if not exists):

buildTypes {

release {
    minifyEnabled false
    manifestPlaceholders.securityConfig = "@xml/network_security_config_prod"
 }

 debug {
    manifestPlaceholders.securityConfig = "@xml/network_security_config_dev"
 }

}

in AndroidManifest.xml use securityConfig placeholder as following (which was defined in build.gradle):

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:networkSecurityConfig="${securityConfig}"   <------- here
Wsan answered 27/10, 2022 at 23:22 Comment(1)
Why do I see this answer first? No mention of security concerns, nothing! I mean one cannot simply disable a security feature that prevents MITM, eavesdropping, etc. Your answer correctly solves the OP problem, though.Industry
P
9

To apply these various answers to Xamarin.Android, you can use class and assembly level Attributes vs. manually editing the AndroidManifest.xml

Internet permission of course is needed (duh..):

[assembly: UsesPermission(Android.Manifest.Permission.Internet)]

Note: Typically assembly level attributes are added to your AssemblyInfo.cs file, but any file, below the using and above the namespace works.

Then on your Application subclass (create one if needed), you can add NetworkSecurityConfig with a reference to an Resources/xml/ZZZZ.xml file:

#if DEBUG
[Application(AllowBackup = false, Debuggable = true, NetworkSecurityConfig = "@xml/network_security_config")]
#else
[Application(AllowBackup = true, Debuggable = false, NetworkSecurityConfig = "@xml/network_security_config"))]
#endif
public class App : Application
{
    public App(IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer) : base(javaReference, transfer) { }
    public App() { }

    public override void OnCreate()
    {
        base.OnCreate();
    }
}

Create a file in the Resources/xml folder (create the xml folder if needed).

Example xml/network_security_config file, adjust as needed (see other answers)

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

You can also use the UsesCleartextTraffic parameter on the ApplicationAttribute:

#if DEBUG
[Application(AllowBackup = false, Debuggable = true, UsesCleartextTraffic = true)]
#else
[Application(AllowBackup = true, Debuggable = false, UsesCleartextTraffic = true))]
#endif
Presignify answered 6/5, 2019 at 0:13 Comment(4)
How does this work if you are not on a doamin and on a local host address of 192.168 the applicaiton will not be live out on the internet but a local networkLicketysplit
and what is the syntax for xamrian formsLicketysplit
@rogue39nin Use the last part of my answer : UsesCleartextTraffic = truePresignify
UsesCleartextTraffic worked perfectly - thank you.Apple
F
6

While the working answer, for me, was this by @PabloCegarra:

<?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>

You may receive a security warning regarding the cleartextTrafficPermitted="true"

If you know the domains to 'white list' you should mix both accepted answer and the above one:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">books.google.com</domain>
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </domain-config>
</network-security-config>

This code is working for me, but my app needs to retrieve data from books.google.com only. By this way the security warning disappears.

Faustena answered 26/1, 2020 at 12:3 Comment(0)
P
6
 cleartext support is disabled by default.Android in 9 and above

 Try This one I hope It will work fine

1 Step:->  add inside android build gradle (Module:App)
            useLibrary 'org.apache.http.legacy'

  android {
               compileSdkVersion 28
              useLibrary 'org.apache.http.legacy'

          }

Then 2 Step:-> manifest add inside manifest application tag

<application
    android:networkSecurityConfig="@xml/network_security_config">//add drawable goto Step 4

   // Step --->3  add to top this line  
     <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />

</application>

//Step 4-->> Create Drawable>>Xml file>>name as>> 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>
Phillipphillipe answered 18/2, 2020 at 11:48 Comment(5)
Is it possible to change this in aosp?Halmstad
@Halmstad Yes you can change it.Phillipphillipe
May I know where exactly I can change it?Halmstad
@Halmstad <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">www.yourwebsidedomain.com</domain> </domain-config>Phillipphillipe
No!! Again you are saying in application side. I am asking how to change in framework/<> folder class?Halmstad
P
5

I am also got the same "Cleartext HTTP traffic not permitted" error while developing my Application. I am using Retrofit2 for network calls in my application and I have two project environments(dev & production). My Production domain is having SSL certificate with HTTPS calls and dev won't have https. The configuration is added in the build flavors. But when I change to dev, this issue will trigger. So I have added below-solution for that.

I have added cleartext traffic in the manifest

 android:usesCleartextTraffic="true"

Then I have added a connection spec in the retrofit configuration class OKHttp creation time.

 .connectionSpecs(CollectionsKt.listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT))

Complete OkHttpClient creation is given below

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(10, TimeUnit.SECONDS)
        .connectTimeout(10, TimeUnit.SECONDS)
        .cache(null)
        .connectionSpecs(CollectionsKt.listOf(ConnectionSpec.MODERN_TLS, ConnectionSpec.CLEARTEXT))
        .addInterceptor(new NetworkInterceptor(context))
        .addInterceptor(createLoggingInterceptor())
        .addInterceptor(createSessionExpiryInterceptor())
        .addInterceptor(createContextHeaderInterceptor())
        .build();
Prismatoid answered 18/6, 2019 at 15:38 Comment(0)
T
5

Update December 2019 ionic - 4.7.1

<manifest xmlns:tools=“http://schemas.android.com/tools”>

<application android:usesCleartextTraffic=“true” tools:targetApi=“28”>

Please add above content in android manifest .xml file

Previous Versions of ionic

  1. Make sure you have the following in your config.xml in Ionic Project:

    <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" />
                <application android:usesCleartextTraffic="true" />
            </edit-config>
    
  2. Run ionic Cordova build android. It creates Android folder under Platforms

  3. Open Android Studio and open the Android folder present in our project project-platforms-android. Leave it for few minutes so that it builds the gradle

  4. After gradle build is finished we get some errors for including minSdVersion in manifest.xml. Now what we do is just remove <uses-sdk android:minSdkVersion="19" /> from manifest.xml.

    Make sure its removed from both the locations:

    1. app → manifests → AndroidManifest.xml.
    2. CordovaLib → manifests → AndroidManifest.xml.

    Now try to build the gradle again and now it builds successfully

  5. Make sure you have the following in Application tag in App → manifest → Androidmanifest.xml:

    <application
    android:networkSecurityConfig="@xml/network_security_config"  android:usesCleartextTraffic="true" >
    
  6. Open network_security_config (app → res → xml → network_security_config.xml).

    Add the following code:

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

Here xxx.yyyy.com is the link of your HTTP API. Make sure you don't include any Http before the URL.

Note: Now build the app using Android Studio (Build -- Build Bundle's/APK -- Build APK) and now you can use that App and it works fine in Android Pie. If you try to build app using ionic Cordova build android it overrides all these settings so make sure you use Android Studio to build the Project.

If you have any older versions of app installed, Uninstall them and give a try or else you will be left with some error:

App not Installed

Triplicity answered 7/11, 2019 at 9:51 Comment(2)
ionic? Cordova? So it isn't a normal Android build, but a framework to build native apps with front end tech instead.Rittenhouse
Ionic provides u the webivew implementation in android app and Cordova helps u to access android native features like microphone, camera.Triplicity
T
4

Create file - res / xml / network_security.xml

In network_security.xml ->

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

Open AndroidManifests.xml :

 android:usesCleartextTraffic="true" //Add this line in your manifests

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
Tremolite answered 23/10, 2019 at 15:34 Comment(0)
W
4

Put following into your resources/android/xml/network_security_config.xml :

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

This solves Failed to load resource: net::ERR_CLEARTEXT_NOT_PERMITTED problem on Android for Cordova / Ionic.

Wassail answered 17/6, 2020 at 8:44 Comment(0)
O
3

Just add android:usesCleartextTraffic="true" inside the in AndroidManifest.xml file

Oof answered 17/10, 2019 at 1:15 Comment(0)
E
3

videoView can't open this video Online video

Create file res/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>
</network-security-config>

New in the AndroidManifest.xml file under application:

android:networkSecurityConfig="@xml/network_security_config"

https://techprogrammingideas.blogspot.com/2021/02/android-code-for-displaying-video-with.html

https://youtu.be/90hWWAqfdUU
Evacuation answered 24/2, 2021 at 16:31 Comment(1)
Yes, this works for me, Android 10/11/12.Zipah
T
2

In my case that URL is not working in browser also.

I check with https://www.google.com/

webView.loadUrl("https://www.google.com/")

And it worked for me.

Trestlework answered 14/8, 2019 at 9:57 Comment(3)
myWebView.loadUrl("www.site.com"); is also works for webmasters don't have SSL as HTTPS but have HTTP only. Might get blank page but.Galling
if given url is worked in your web browser then you can use in your webview. otherwise you can see this error.Trestlework
I know sometimes it gives an error, but most of the time I see blank page even run.javascript is "true" and I can access the website correctly. I don't know why I see blank page, also I set zoom-able true.Galling
G
2

For Xamarin.Android developers make sure HttpClient implementation and SSL/TLS is set to Default.

It can be found under Andorid Options -> Advanced Android Options.

enter image description here

Guntar answered 19/11, 2019 at 5:33 Comment(0)
R
2

This is done for security reasons, you should always prefer to use HTTPS (HTTP Secure) where possible.
You can read more about it here

There are multiple solutions for this issue depending on your condition.

If you are trying to communicate with a first party service, IE: your own web server

Server side: You should add HTTPS support to that server and use HTTPS instead of HTTP. These days you can even do it for free using services like LetsEncrypt and others
Client side: If you are using the HttpURLConnection from the java.net package you can switch to HttpsURLConnection of the java.net.ssl package, it has a similar if not identical API, so the switch should be effortless.

If you are using a third party service, like Google, Facebook, a weather service, etc.

In case that the service you are communicating with supports HTTPS (which it most likely does) you can just change your request URL from http://abc.xyz to https://abc.xyz.

As a last resort, if the third party service that you want to communicate with does not support HTTPS or any other form of secure communication, you can use this answer, but again, this is not recommended as it defeats the purpose of this much needed security feature.

Rotman answered 22/12, 2019 at 15:57 Comment(1)
The problem with this is that the vast majority of servers do not run https. It gets offloaded at the load balancer sitting in front of a farm. To run with TLS I need to install nginx and offload SSL with that to 8080 or whatever on localhost. Because hey, I am not testing Android here but the backend. So I cannot be building apk's.Normalie
A
2

If you are using ionic and getting this error during native http plugin, following fix needs to be done-

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>

That worked for me!

Atmo answered 1/4, 2020 at 8:25 Comment(0)
S
2

I using Cordova 8 with cordova-plugin-whitelist 1.3.4 and it default configuration my app no access to internet and i only add a parameter in the manifest.xml -> android:usesCleartextTraffic="true"

The path of mainfest changed in Cordova 8: platform/android/app/src/main/AndroidManifest.xml.

 <?xml version='1.0' encoding='utf-8'?>
    <manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" package="io.cordova.hellocordova" xmlns:android="http://schemas.android.com/apk/res/android">
        <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
        <application 
android:hardwareAccelerated="true" 
android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:supportsRtl="true" 
android:usesCleartextTraffic="true">
            <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
                <intent-filter android:label="@string/launcher_name">
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    </manifest>

this is a real stupid because it obvious that your app need access to internet....

Swen answered 17/5, 2020 at 4:29 Comment(0)
T
1

Upgrade to React Native 0.58.5 or higher version. They have includeSubdomain in their config files in RN 0.58.5.

ChangeLog

In Rn 0.58.5 they have declared network_security_config with their server domain. Network security configuration allows an app to permit cleartext traffic from a certain domain. So no need to put extra effort by declaring android:usesCleartextTraffic="true" in the application tag of your manifest file. It will be resolved automatically after upgrading the RN Version.

Thunderstorm answered 26/3, 2019 at 8:48 Comment(0)
C
1

After changed API version 9.0 getting the error Cleartext HTTP traffic to YOUR-API.DOMAIN.COM not permitted (targetSdkVersion="28"). in xamarin, xamarin.android and android studio.

Two steps to solve this error in xamarin, xamarin.android and android studio.

Step 1: Create file resources/xml/network_security_config.xml

In network_security_config.xml

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

Step 2: update AndroidManifest.xml -

Add android:networkSecurityConfig="@xml/network_security_config" on application tag. e.g:

<application android:label="your App Name" android:icon="@drawable/icon" android:networkSecurityConfig="@xml/network_security_config">
Casque answered 3/8, 2019 at 13:0 Comment(0)
P
1

adding this paramter in header resolved my issue in apiSauce React Native

"Content-Type": "application/x-www-form-urlencoded",
  Accept: "application/json"
Polymeric answered 16/9, 2019 at 12:11 Comment(0)
B
1

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 (not https), it could raise the risk of hacking 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. Here is the implementation and the reference of how to resolve this problem.

Burchell answered 7/4, 2020 at 16:8 Comment(0)
C
1

We were faced with a very similar problem and it was a pain to figure it out. For those unlucky souls who will have to deal with this, here is what we did:

The ionic app was working fine in the browser (Chrome, and Firefox), was deployed to Apple’s App store, and was communicating fine with our API on AWS. Then we went for the Android build. In the emulator, our https API request would not even get sent out. On a physical device, https requests would not get sent out either (after deploying to “internal testing” on Google Play)

Ran our app in the emulator Opened chrome, typed “chrome://inspect”, waited, clicked link to emulator instance, and was able to look at the network tab. The requests would quickly cycle from (pending) to (cancelled), without being sent out to the server.

Looked all over stackoverflow and the main advice was to disable https using the cleartextPermitted workaournd which is a terrible idea.

The other common advice is to use native http, but what’s the point of using ionic if we have to have 2 code bases, and I wanted to keep my http interceptors.

Added a network_security_config.xml file (which is probably not strictly necessary, but it removes a compilation warning in Android Studio.)

Checked the SSL certificate on our servers by clicking on the lock icon in a browser. Looked fine. (perhaps because it really wasn’t, but I there was a manual override that I had added long ago and forgotten about). lots of other tail-chasing…

Finally used sslshopper’s tool to verify our SSL cert: https://www.sslshopper.com/ssl-checker.html

Turns out that while our cert was ok, the chain of certs was not. This will show up as a red broken arrow in their diagnostics.

Basically, you have to take your SSL cert and create a bundle, by appending the SSL certs of the organization that provided your cert, and appending any other SSL certs that certify the certifier, until the whole chain is clean. We had used a provided bundle, but it was not going sufficiently up through the chain.

Fix the SSL chain:

cat your-purchased-cert-site-com.crt > your-site.bundle.crt
cat other-org-cert-sectigoRSA-bla-bla-bla.crt >> your-site.bundle.crt
cat another-org-cert-USERTrust-bla-bla-bla.crt >> your-site.bundle.crt
cat some-final-high-level-org-cert.crt >> your-site.bundle.crt

Then, in our case, for nginx on ubuntu:

put your-site.bundle.crt where it can be used. (in our case, /var/ssl)

update /etc/nginx/sites-available/site-name.conf:
ssl_certificate /var/ssl/your-site.bundle.crt
ssl_certificate /var/ssl/your-private-key.key

and restart your web server (in our case nginx: sudo systemctl restart nginx)

check it with sslshopper’s checker, you should see green arrows all the way.

started our emulator, and the API calls went right through.

Corrianne answered 7/10, 2021 at 18:18 Comment(0)
J
0

Try hitting the URL with "https://" instead of "http://"

Jueta answered 5/5, 2020 at 11:48 Comment(2)
That issue is entirely attributed to secure protocol?Philipp
@Nelles It's but changing protocols is not the right solution. The server may not support SSL connectionsDogtrot
N
0

i had same issue in my simple webview app because my url was http:// but when u turn it to https:// the error got solved.

Neurovascular answered 26/9, 2021 at 6:4 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From ReviewLog
P
0

Check that the domain is the right one in your network_security_config.xml.

In my case I used a command --external with ionic cordova which changed the domain.

SOLUTION 1

Remove the --external

SOLUTION 2

Edit your domain in network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">
       YOUR_DOMAIN (ex: localhost)
    </domain>
</domain-config>
</network-security-config>
Petrapetracca answered 31/1, 2022 at 13:51 Comment(0)
A
0

After trying a lot of alternative solutions finally it came to work with the following change in .NET 8 Maui I have already answered this question in the following thread as well https://mcmap.net/q/35723/-how-to-fix-39-cleartext-http-traffic-to-x-not-permitted-39-in-xamarin-android

Add android:usesCleartextTraffic="true" text to the Application tag under AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:usesCleartextTraffic="true"></application>
</manifest>
Adelaideadelaja answered 13/4 at 18:59 Comment(0)
C
-3

Oneliner to solve your problem. I assume you will store your URL in myURL string. Add this line and you are done. myURL = myURL.replace("http", "https");

Crouton answered 16/4, 2020 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.