简体   繁体   中英

How to test service returning JSON on localhost with android emulator

I've got a dropwizard service running on localhost:8080.

It returns the following json on this url: http://localhost:8080/users/johndoe/items

[
{
"id": 1,
"name": "Item1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 7,
"name": "Item 3"
},
{
"id": 8,
"name": "Item4"
}
]

When I try to access this URL from my android emulator I am getting this exception:

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:8080 refused

In my manifest I've given internet permissions

<!-- Permission - Internet Connect -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

I've also tried to change localhost to 127.0.0.1 to no avail

Question

I understand that the API will need to be put on the server accessible by the internet for production app but for development purposes what is the way to resolve this?

Localhost refers to the address of the emulator. If you want to access the computer which runs the emulator use 10.0.2.2 , which is the default ip address of the host machine.

If you want to test your server on localhost from an Emulator, you have two options :

  1. Call the IP address 10.0.2.2 instead of localhost
  2. Call the router IP address of your computer, starting with 192.168.xx

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM