ChatGPT解决这个技术问题 Extra ChatGPT

Accessing localhost:port from Android emulator

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.

I expected the behaviour, that not all ports are forwarded... 5555 was not forwarded but 8080 and 8081 worked just fine...
You need to edit your vs-iis config file: stackoverflow.com/a/50991257/7149454

A
Akhil Jain

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>".

https://i.stack.imgur.com/qF3te.png


Why should it? The error Bad Request means that the localhost server is reachable, but that the request isn't quite correct..
i am not sure, i follow through, what exactly are you saying, is it relevant to provided solution??
Not working for me right now, but here's the link to the Android docs and it's clear that this is what sould do it (10.0.2.2); developer.android.com/tools/devices/emulator.html
obviously this does not clarify anything, Robin is already using 10.0.2.2 ip in the question and it is not working. Although your answer is correct, it does NOT provide a solution.
This answer rounded out the solution for me and got me up and running: stackoverflow.com/a/55606008/738662
d
dKen

Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion


Why 10.0.3.2 for Genymotion ?
@Jacob Because Genymotion is a different emulator and they chose to use a different ip than google's emulator (Which borders on useless. Seriously, when are they going to do something about their awful default emulator?)
In API 28+ you should explicitly allow non-https (clear-text) traffic in your network config too. See my answer below stackoverflow.com/a/56769746/2290369
I
Ismail Yavuz

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'd say this is the correct answer, although it is much easier achieved, adding this to your manifest (as proposed here: stackoverflow.com/questions/51902629/… ) : <application android:usesCleartextTraffic="true"> </application>
If you're using API > 28, check out this answer, this should solve your issue.
I don't know the ip and port. i have my local server running at m.local.sese.com . How do I access it in my emulator?
E
Ehsan Zargar Ershadi

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.


this in conjunction with the 10.0.0.2 url solved it for me. this setting seemed to be overriding the hosting.json approach explained elsewhere.
I'm running django server locally on macOS and usually I access it via http://localhost:5000/ in both Postman and iOS simulator. This solution works for Android simulator and no need to modify my server, nor any settings in simulator. Quick, nice and portable to other computers without extra work.
Android app with xamarin and ASP.NET Web APIs both using VS. WORKED! Thanks!!
This is the easiest way...it worked for me while trying to connect to my api rest developed with .net core 3.1 on VS 2019 from my emulator...Thanks!
n
n370

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.


The easiest one for me. Saved it right to an npm script "android-map-localhost": "adb reverse tcp:54722 tcp:54722"!
C
Community

If you are using IIS Express you may need to bind to all hostnames instead of just `localhost'. Check this fine answer:

https://stackoverflow.com/a/15809698/383761

Tell IIS Express itself to bind to all ip addresses and hostnames. In your .config file (typically %userprofile%\My Documents\IISExpress\config\applicationhost.config, or $(solutionDir).vs\config\applicationhost.config for Visual Studio 2015), find your site's binding element, and add

Make sure to add it as a second binding instead of modifying the existing one or VS will just re-add a new site appended with a (1) Also, you may need to run VS as an administrator.


No, you don't always need to use blank host name, blog.lextudio.com/…
this was the way IIS Express liked where 15000 was my port and then pointing to 10.0.2.2:15000 on the android emulator
After trying different options this solution is the only one that has worked! Many thanks
No work! If I modify the port of the file and then the web server cannot run.
R
Ronny Morán

I solved it with the installation of "Conveyor by Keyoti" in Visual Studio Professional 2015. Conveyor generate a REMOTE address (your IP) with a port (45455) that enable external request. Example:

https://i.stack.imgur.com/MmufI.png

Conveyor allows you test web applications from from external tablets and phones on your network or from Android emulators (without http://10.0.2.2:<hostport>)

The steps are in the following link :

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti


What if you don't run the webserver within Visual Studio? Imo, this isn't an answer to the question.
I try but after some days later the given URL is not working and don't find any soluations.
After a long struggle, the only thing that did the trick was installing this extension and enabling the Remote URL feature. It takes the request a bit longer to hit the API, but it works.
C
Cobus Kruger

The problem is that the Android emulator maps 10.0.2.2 to 127.0.0.1, not to localhost. So configure your web server to serveron 127.0.0.1:54722 and not localhost:54722. That should do it.


A
Akhil Jain

I have a webserver running on my localhost.

If I open up the emulator and want to connect to my localhost I am using 192.168.x.x. This means you should use your local lan ip address. By the way, your HttpResponseException (Bad Request) doesn't mean that the host is not reachable.

Some other errors lead to this exception.


M
Md Imran Choudhury

After running your local host you get http://localhost:[port number]/ here you found your port number.

https://i.stack.imgur.com/w8pXH.png

In my case, IP was 192.168.10.33 so my URL will be http://192.168.10.33:[port number]/. In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.

https://i.stack.imgur.com/gVPZo.png


My Android Studio is Chipmunk| 2021.2.1 Patch1. And My Emulator Settings does not have proxy tab. Could you tell me what version of your Android Studio ? Or is there a way to solve this problem?
L
Lavish

To access localhost on Android Emulator

Add the internet permission from AndroidManifest.xml

Add android:usesCleartextTraffic="true", more details here:

Run the below-mentioned command to find your system IP address:

ifconfig | grep "inet " | grep -v 127.0.0.1

Copy the IP address obtained from this step (A)

Run your backend application, which you can access at localhost or 127.0.0.1 from your sytem.

Now in android studio, you can replace the URL if you're using in code or You can use the ip address obtained from step(A) and try opening in web browser, Like this http://192.168.0.102:8080/

Don't forget to add PORT after the IP address, in my case app was running on 8080 port so I added IP obtained in (A) with the port 8080


Hey, this worked! but is there any way to have this set up permanently so that I don't have to change it every time? I'd rather not have to look up my IP every time and just have the emulator recognize that localhost means the host machine.
If you're worried of changing in code every-time, better to have a hostname there that you can resolve locally. So that there will be no code change, and the IP will be resolved locally. This link might be helpful tecmint.com/setup-local-dns-using-etc-hosts-file-in-linux for setting up host to resolve locally. To make this flow automatically, I didn't find any :)
A
Akhil Jain

you need to set URL as 10.0.2.2:portNr

portNr = the given port by ASP.NET Development Server my current service is running on localhost:3229/Service.svc

so my url is 10.0.2.2:3229

i'd fixed my problem this way

i hope it helps...


I have a custom url for my localhost and I don't know the port number. This is my url m.local.sese.com .
I believe in this case you need to set portNr on DNS for that domain
C
Community

"BadRequest" is an error which usually got send by the server itself, see rfc 2616

10.4.1 400 Bad Request The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

So you got a working connection to the server, but your request doesn't fit the expecet form. I don't know how you create the connection, what headers are included (if there are any) – but thats what you should checking for.

If you need more help about, explain what your code is about and what it uses to connect to the Server, so we have the big picture.

Here is a question with the same Problem – the answer was that the content-type wasnt set in the header.


You got the right point, but went the wrong direction afterwards. The next step should be analyzing the server to learn what kind of requests it cares about, so as to understand why requests from the emulators are replied with 400. A case study for IIS Express can be found here, blog.lextudio.com/…
A
Ameya Salagre

1) Run ipconfig command in cmd

https://i.stack.imgur.com/dt0MG.jpg

3) Then use IPv4 Address of VMWare Network Adapter 1 followed by port number

In My Case its 8080, so instead of using localhost:8080

I am using 192.168.56.1:8080

https://i.stack.imgur.com/jdHQ1.png

Done.....


Port number is what you set in xamp apache port
C
Community

I would like to show you the way I access IISExpress Web APIs from my Android Emulator. I'm using Visual Studio 2015. And I call the Android Emulator from Android Studio.

All of what I need to do is adding the following line to the binding configuration in my applicationhost.config file

<binding protocol="http" bindingInformation="*:<your-port>:" />

Then I check and use the IP4 Address to access my API from Android emulator

Requirement: you must run Visual Studio as Administrator. This post gives a perfect way to do this.

For more details, please visit my post on github

Hope this helps.


Or install the free VS Extension called Conveyor from the Extensions window. That opens up IIS Express to outside requests without changing the config.
You do have other options, blog.lextudio.com/… than running VS as admin. So I won't call that a must.
N
Nomi

For Laravel Homestead Users: If anyone using Laravel with homestead you can access app backend using 192.168.10.10 in emulator

Still not working? Another good solution is to use ngrok https://ngrok.com/


ngrok can only be run on internet, slow internet may cause network failure request.
w
winiex

I am using Windows 10 as my development platform, accessing 10.0.2.2:port in my emulator is not working as expected, and the same result for other solutions in this question as well.

After several hours of digging, I found that if you add -writable-system argument to the emulator startup command, things will just work.

You have to start an emulator via command line like below:

 emulator.exe -avd <emulator_name> -writable-system

Then in your emulator, you can access your API service running on host machine, using LAN IP address and binding port:

http://192.168.1.2:<port>

Hope this helps you out.

About start emulator from command line: https://developer.android.com/studio/run/emulator-commandline.


k
kakopappa

I had the same issue when I was trying to connect to my IIS .NET Webservice from the Android emulator.

install npm install -g iisexpress-proxy iisexpress-proxy 53990 to 9000 to proxy IIS express port to 9000 and access port 9000 from emulator like "http://10.0.2.2:9000"

the reason seems to be by default, IIS Express doesn't allow connections from network https://forums.asp.net/t/2125232.aspx?Bad+Request+Invalid+Hostname+when+accessing+localhost+Web+API+or+Web+App+from+across+LAN


u
user2368055

localhost seemed to be working fine in my emulator at start and then i started getting connection refused exception i used 127.0.2.2 from the emulator browser and it worked and when i used this in my android app in emulator it again started showing the connection refused problem.

then i did ifconfig and i used the ip 192.168.2.2 and it worked perfectly


k
karthik

Bad request generally means the format of the data you are sending is incorrect. May be mismatched data mapping . If you are getting bad request implies you are able to connect to the server, but the request is not being sent properly.


s
skillworks

If anybody is still looking for this, this is how it worked for me.

You need to find the IP of your machine with respect to the device/emulator you are connected. For Emulators on of the way is by following below steps;

Go to VM Virtual box -> select connected device in the list. Select Settings ->Network-> Find out to which network the device is attached. For me it was 'VirtualBox Host-Only Ethernet Adapter #2'. In virtualbox go to Files->Preferences->Network->Host-Only Networks, and find out the IPv4 for the network specified in above step. (By Hovering you will get the info)

Provide this IP to access the localhost from emulator. The Port is same as you have provided while running/publishing your services.

Note #1 : Make sure you have taken care of firewalls and inbound rules.

Note #2 : Please check this IP after you restart your machine. For some reason, even If I provided "Use the following IP" The Host-Only IP got changed.


D
Denis Wang

I resolved exact the problem when the service layer is using Visual Studio IIS Express. Just point to 10.0.2.2:port wont work. Instead of messing around the IIS Express as mentioned by other posts, I just put a proxy in front of the IIS Express. For example, apache or nginx. The nginx.conf will look like

 # Mobile API
 server { 
    listen       8090;
    server_name  default_server;

    location / {
        proxy_pass http://localhost:54722;
    }
  }

Then the android needs to points to my IP address as 192.168.x.x:8090


P
Post Impatica

if you are using some 3rd party package like node express or angular-cli you will need to find the IP of your machine, and attach your host to that IP within the server startup config (instead of localhost). Then launch it from the emulator using the IP. For example, I had to use: ng serve -H 10.149.212.104 to use the angular-cli. Then from the emulator I used: http://10.149.212.104:4200


D
DenisKolodin

Explanation why localhost is not available from emulators for anyone who has basic access problem. For sophisticated cases read other answers.

Problem: Emulator has own local network and localhost maps itself to emulator, but NOT your host!

Solution:

Bind your server to 0.0.0.0 to make it available for emulator's network Get external IP address of your laptop: ifconfig command for Mac In Android (or Flutter app) use IP address of your external interface like: 192.168.1.10 instead of localhost


z
zia khan

If you are working with Asp.Net Web API, in .vs/config folder inside your project, modify these lines as per you port setting. Let suppose you use port 1234 and physicalPath to the project folder set by IIS is "D:\My Projects\YourSiteName", then

<site name="YourSiteName" id="1">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="D:\My Projects\YourSiteName" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:1234:*" />
                </bindings>
            </site>

In android studio, access your api with "http://10.0.2.2:1234" ...