'How to fix 'Cleartext HTTP traffic to x not permitted' in xamarin android

I have an issue in my application Cleartext HTTP traffic to x not permitted.

I've already tried putting android:usesCleartextTraffic="true" in my manifest. But i want to change "android:usesCleartextTraffic" flag to "false" to prevent unencrypted traffic from being sent.

How to solve this?



Solution 1:[1]

You can fix this with one line of code. Open AssemblyInfo.cs in your android project under properties and add the code below:

[assembly: Application(UsesCleartextTraffic = true)]

Solution 2:[2]

If at some point you want to move to MAUI (which has no AssemblyInfo.cs), you might want to add UsesCleartextTraffic) to your Application attribute in Platforms/Android/MainApplication.cs:

#if DEBUG
[Application(UsesCleartextTraffic = true)]  // connect to local service
#else                                       // on the host for debugging,
[Application]                               // access via http://10.0.2.2
#endif
public class MainApplication : MauiApplication
{
    ...
}

Solution 3:[3]

In Maui, expand Platforms/Android and edit MainApplication.cs.

Replace "[Application]", near the top, with "[Application(UsesCleartextTraffic = true)]"

Solution 4:[4]

Assuming you are accessing a server that doesn't support HTTPS, then you can create exceptions in your network security config. You can create a file net_sec_conf.xml like this:

<?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">api.example.org</domain>
    <trust-anchors>
      <certificates src="system" />
    </trust-anchors>
  </domain-config>
</network-security-config>

and then in manifest file add this line:

android:networkSecurityConfig="@xml/net_sec_conf"

(assuming you have put the file in xml folder). This way cleartext HTTP traffic will only be allowed for the specified domain.

Of course, if the server supports HTTPS, then you just need to change your URL "http://..." to "https://...".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mordecai
Solution 2 thomiel
Solution 3 Mike
Solution 4