How to connect and run localhost api in android studio

Here in this post, we'll see how to connect or call a localhost endpoint or API when we are developing a real android application.

but before knowing the trick, let's understand what is localhost and how it works?

So our endpoint is nothing but it's a URL.☝☝☝

URL -๐Ÿ‘‰ Uniform Resource Locator

http://localhost:6000/somepath

http - Name of Protocol

localhost - Hostname or Domain Name

6000 - port number (just for example)

somepath - any path which represents your data/task

so if we talk about hostname or domain name - some examples are below๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

www.google.com
www.amazon.in

These are hostname or domain names, but actually, they are representing an IP address, 
These domain names have been bound with a specific and unique IP address, as IP address is hard to remember, that's why we got domain name which is very easy to remember.

Here we just have to use these hacks for our use.

In our case, localhost means is that our services are running in our local system on a specific port.

So instead of localhost we just have to use our system's IP address.

Step 1 -

Press windows+R enter cmd and press enter or search for cmd in the windows search area.

Step 2 -

type ipconfig in cmd and press enter.

C:\Users\Asus>ipconfig

Step 3 - 

You will see some information on cmd, 

find the value of IPv4 Address and copy that.

IPv4 Address. . . . . . . . . . . : xxx.xxx.xx.xxx

using x just for example here you'll find some numeric value.

this is your IP address.

So now our endpoint or API looks like  -   

http://localhost:6000/yourpath                    ❌

http://xxx.xxx.xx.xxx:6000/yourpath           ✅

Now just follow some below step and you will be able to access your localhost endpoint while developing an android application.

1 -  Your device and your PC\Laptop should be connected to the same WiFi network.
2 - Define ur base URL in your application code with IP address, not with localhost.
3 - Connect your device with android studio and launch the Application on the device.

 
follow the link below


4- If all is good you'll easily access localhost in your application.

That's all about this post.

Thanks a bunch for being here.
#stayhealthy
#takeCare

*************
******************
*************************



No comments:

Post a Comment