I'm running a web service on my local machine that runs at localhost:54722
.
I want to call the service from an app running in the Android emulator.
I read that using 10.0.2.2
in the app would access localhost, but it doesn't seem to work with the port number as well. It says HttpResponseException: Bad Request
.
You can access your host machine with the IP address "10.0.2.2
".
This has been designed in this way by the Android team. So your webserver can perfectly run at localhost and from your Android app you can access it via "http://10.0.2.2:<hostport>
".
If your emulator must access the internet through a proxy server, you can configure a custom HTTP proxy from the emulator's Extended controls screen. With the emulator open, click More , and then click Settings and Proxy. From here, you can define your own HTTP proxy settings.
Use 10.0.2.2
for default AVD and 10.0.3.2
for Genymotion
Since 10.0.2.2
is not a secure domain for Android you have to allow non-secured domains in your network configuration for API 28+ where non-TLS connections are prevented by default.
You may use my following configurations:
Create a new file in main/res/xml/network_security_config.xml as:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
And point it in AndroidManifest.xml
<application
......
......
android:networkSecurityConfig="@xml/network_security_config">
I faced the same issue on Visual Studio executing an web app on IIS Express. to fix it you need to go to your project properties then click on Debug Tab and change http://localhost:[YOUR PORT] to http://127.0.0.1:[YOUR PORT] and set the android url to http://10.0.2.2:[YOUR PORT]. it worked for me.
I'm not sure this solution will work for every Android Emulator and every Android SDK version out there but running the following did the trick for me.
adb reverse tcp:54722 tcp:54722
You'll need to have your emulator up an running and then you'll be able to hit localhost:54722
inside the running emulator device successfully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With