When accessing the local server through localhost or 127.0.0.1 in Android development, the exception java.net. ConnectException: localhost/127.0.0.1: 8083-Connection refused is reported.
Why is this exception reported? Because the Android simulator treats itself as localhost or 127.0.0.1, And then we access the local server through localhost or 127.0.0.1, an exception is thrown.
I checked it online. On the simulator, I can use 10.0.2.2 to replace 127.0.0.1 and localhost;
In addition, in the LAN environment, you can use 192.168.0.x or 192.168.1.x (depending on the configuration) to connect to the local machine. In the LAN environment, we can use the Android code to obtain the IP address of the local server. Next we will use the code to demonstrate how to obtain the IP address that Android can access the local server.
Step 1: Add the following permissions to the configuration file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Step 2: Obtain the Android local IP address and MAC address
Package cn. itcast. test;
Import java.net. InetAddress;
Import java.net. NetworkInterface;
Import java.net. SocketException;
Import java. util. Enumeration;
Import java. util. List;
Import android. content. Context;
Import android.net. wifi. WifiInfo;
Import android.net. wifi. WifiManager;
Import android. test. AndroidTestCase;
Import android. util. Log;
Import cn. itcast. domain. Video;
Import cn. itcast. news. MainActivity;
Import cn. itcast. service. VideoService;
Public class VideoServiceTest extends AndroidTestCase {
Private static final String TAG = "VideoServiceTest ";
Public void testLocalIpAndMac (){
Log. I (TAG, "IP:" + getLocalIpAddress () + ", MAC:" + getLocalMacAddress ());
}
/**
* Obtain the Android local IP Address
*
* @ Return
*/
Private String getLocalIpAddress (){
Try {
For (Enumeration <NetworkInterface> en = NetworkInterface
. GetNetworkInterfaces (); en. hasMoreElements ();){
NetworkInterface intf = en. nextElement ();
For (Enumeration <InetAddress> enumIpAddr = intf
. GetInetAddresses (); enumIpAddr. hasMoreElements ();){
InetAddress inetAddress = enumIpAddr. nextElement ();
If (! InetAddress. isLoopbackAddress ()){
Return inetAddress. getHostAddress (). toString ();
}
}
}
} Catch (SocketException ex ){
Log. e ("WifiPreference IpAddress", ex. toString ());
}
Return null;
}
/**
* Obtain the MAC address of the Android host.
*
* @ Return
*/
Private String getLocalMacAddress (){
WifiManager wifi = (WifiManager) this. getContext (). getSystemService (Context. WIFI_SERVICE );
WifiInfo info = wifi. getConnectionInfo ();
Return info. getMacAddress ();
}
}
Running result
10.0.2.15 is the IP address.