Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving data from localhost throws 'Connection Refused Error' [duplicate]

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.

like image 295
Robin Avatar asked Jul 20 '11 10:07

Robin


5 Answers

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 dots, and then click Settings and Proxy. From here, you can define your own HTTP proxy settings. screen-shot for HTTP config

like image 120
Akhil Jain Avatar answered Sep 23 '22 13:09

Akhil Jain


Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion

like image 29
Vinod Joshi Avatar answered Sep 20 '22 13:09

Vinod Joshi


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">
like image 22
Ismail Yavuz Avatar answered Sep 22 '22 13:09

Ismail Yavuz


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.

like image 44
Ehsan Zargar Ershadi Avatar answered Sep 24 '22 13:09

Ehsan Zargar Ershadi


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.

like image 23
n370 Avatar answered Sep 23 '22 13:09

n370