Connecting to localhost in Android - android

I'm developing an App and have designed a bit of Frontend and backend, just the essential. And now, I want to connect both sides. First of all, I need to know how to connect to a localhost in Android.
I tried some tutorials in Internet using for example:
URL url = new URL("http://127.0.0.1");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
I've tried several approaches but all of them fail. Some doesn't do anything and others stop the App showing some Zygote errors.
My question is clear. How can I connect to localhost in Android? I want a function of the style makeConnectionLocalHost() that returns whether the connection has been successful or not. Any idea why nothing works?

Try instead of using "localhost" your local ip. To retrieve it, open CMD and type ipconfig. There you will find your local ip.
127.0.0.1 will create a loop back to your own device.

You can use InetAddress.getLocalHost() to get localhost address. More details here. And for HttpURLConnection you should have Web-server on this address.

Related

java.net.UnknownHostException: Unable to resolve host [LOCAL]

I use the INTERNET uses-permission in the manifest file.
If I type URL url = new URL('http://www.example.com/page') (remote server) it will work.
But if I type URL url = new URL('http://example.local/page') (local server) it will return the error
java.net.UnknownHostException: Unable to resolve host "example.local": No address associated with hostname
Now in %WINDIR%/System32/drivers/etc/hosts I wrote this entry :
10.101.0.179 example.local
I can't use new URL('http://10.101.0.179/page') because example.local is a virtualHost in my apache configuration.
Can't my AVD looks into the hosts file ? what should I do to tell android to fetch the ip 10.101.0.179 but still send a proper information to apache and tell it to serve the virtual host example.local ?
If you try to request a web-page from your local HTTP server and the page is bounded to a virtualHost, so let say you need to reach http://example.local/mypage and if as pointed by #CommonsWare you don't use mDNS to resolve inter-local domain-names, android will probably throw the same error message as it reads in the title of this question. Here's the solution I am using :
let's say http://example.local/mypage refers to the ip address 10.101.0.179, Android won't be able to resolve example.local, you need to write the raw url (of your actual local server)
try {
...
URL url = new URL("http://10.101.0.179/mypage");
HttpUrlConnection conn = (HttpUrlConnection) url.openConnection();
...
}
...
But now when Apache receives this request, unless serving your desired host, 10.101.0.179 won't be understood in case of a VirtualHost. To round-about this problem, just modify the Host http-header property using setRequestProperty :
...
conn.setRequestProperty("Host", "example.local");
...
And it should work.
First you must check if you have given INTERNET permission in your manifest file or not, second you make sure that your emulator or computer has a valid internet. If it doesn't work than you can do following:
If you are using localhost url than you must convert that url into IP address to work with App specially using Android emulator.
For example :
My Current url is
http://mylocaladdress:9090/myapp.svc/ForgetPassword?EmailID=test#test.com
Now you can put the following command into terminal on mac or you can use cmd on windows
ping mylocaladdress
The result will give u the IP address and my final url becomes
http://10.1.2.111:9090/myapp.svc/ForgetPassword?EmailID=test#test.com
This url worked perfectly in android emulator without exception.

Getting access to localhost by using webservice in my Android device

I'm trying to test an Android aplication that uses webservice to access localhost.
My device ip is 192.168.0.21 and my localhost ip is 192.168.0.22.
I tried this:
HttpsURLConnection conn;
Url url = new URL("http://192.168.0.22:80/admapp/adm_service.php?");
conn = (HttpsURLConnection) url.openConnection();
It does not work. I've tried to disable the firewall and nothing.
I'm using EasyPHP, but I think that this don't matter.
Could anyone help me?
It should work if you map your IP to localhost in hosts file. The file will be at C:\Windows\System32\drivers\etc\hosts in windows, /etc/hosts in Linux.

Captive Portal Page with MITM

I have a micro-computer designed to show customers a portal page when they sign-in the Wi-Fi network.
The problem is that for some reason they don't get the usual popup from the phone/pc where as when I do the same with my router it works.
I'm doing the whole process by transferring all dns request to a local network (i.e 10.0.0.2).
When going to the browser they get the portal page, but the behaviour is missing. (connecting to the Wi-Fi then an automatic popup appears saying that you need to log in to the network).
on the local apache i have a simple index.php file with status code of 401 (unauthorised).
The micro-computer is connected via Ethernet port to the router, and I have full-control of the router, yet I want the captive portal be managed from the micro-computer itself, thats why I'm not using router based captive portals.
Tal.
Your question isn't very clear to me.
Are you using a browser on the phone/pc or an application? Can you provide a screenshot of the expected behavior?
I'll try to answer it from what I think you are asking:
For a browser, you can use your DNS or ICMP to redirect a client to your Captive Portal. ICMP is layer 3 protocol and some platforms (like Android) might automatically trigger a native notification to the user, like "Hey you need to sign in". But the DNS redirect won't trigger this, it requires user interaction with a browser after connecting to the network. They'll open a browser, try to go to stack overflow.com and get redirect to your captive portal.
Also, for an application on Android, you have to check a URL connection. Here is an example taken from AOSP:
private static final String mWalledGardenUrl = "http://clients3.google.com/generate_204";
private static final int WALLED_GARDEN_SOCKET_TIMEOUT_MS = 10000;
private boolean isWalledGardenConnection() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(mWalledGardenUrl); // "http://clients3.google.com/generate_204"
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setConnectTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS);
urlConnection.setReadTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS);
urlConnection.setUseCaches(false);
urlConnection.getInputStream();
// We got a valid response, but not from the real google
return urlConnection.getResponseCode() != 204;
} catch (IOException e) {
if (DBG) {
log("Walled garden check - probably not a portal: exception "
+ e);
}
return false;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
Solutions :
Possibility 1 :
You need to have a very specific configuration on your router because he is the relay to your Micro-Computer, plus as i guess your micro-computer is going to internet through the router, you also need to take that in consideration
Disable DNS Service on your router
Set DNS on your router to 10.0.0.2
Disable gateway to Internet on your router or set it to 10.0.0.2
Set all real servers/gateway manually on your Micro-Computer, and also routes are very important in this case.
Possibility 2 :
Don't forget that some devices have their DNS set manually or with specific network configuration or having a specific firewall that watch uncommon DNS server/request then you have to take that in consideration, best solution to avoid that is running the DNS Server on the gateway ip it mean that your DHCP Server need to be on the Mini-Computer or use a gateway on the Mini-Computer or use possibility 3... this imply checking the gateway that you are using i guess it's the router gateway.
Also you could have a conflict between router job and Micro-Computer Job, and ip conflict like communication between client and Micro-Computer blocked in some case, then check your ip configuration.
Possibility 3 :
If your router is open-source ou open-source convertible you can use DDWRT or OpenWRT to manage your hotspot there are a plenty of configurable hotspots in just few click and you can link them to your Micro-Computer server for users data base or dns or proxy or dhcp or redirect the request to your Micro-Computer or whatever.
Possibility 4 :
Have a look at this MITM Guide and check if you are missing something
Note :
If my answer did not help please provide more technical debugging infos because other than just a description of the configuration we don't know much... i'll be pleased to help :)... also give full config of your network it seems that it's a network issue.

Android how to make GET or POST Http Request using url with an IP address instead of HostName

Hi all I am trying to send data to my development database from android application using Post but am getting exception
09-18 15:23:36.801: W/System.err(6755): java.io.FileNotFoundException: http://10.255.162.84:8080/web/events
09-18 15:23:36.801: W/System.err(6755): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
If I copy paste the url the web browser in my computer. the webpage I am trying to get works.
If I replace the url with https:www.google.com in my application, it works.
What does this mean? I can't connect make http connection without a host name?
code
URL url = new URL("http://10.255.162.84:8080/web/events");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(20000 /*millis*/);
conn.setConnectTimeout(15000 /*millis*/);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
System.out.println(conn.getResponseCode());
InputStream is = conn.getInputStream();
Reader reader = new InputStreamReader(is, "UTF-8");
char[] buffer = new char[500];
reader.read(buffer);
System.out.println(new String(buffer));
Additional information
The server to receive get and post requests is running on my PC port 8080 via a broadband connection.
I am running the application on my low end phone running android 2.2 (Froyo)
I hope that's all the relevant information but am glad to provide more. I know you get this all the time but I swear to you I am really new to android
I'm guessing your android device is not on the same network as your computer. You can test this easily by pasting the url into an android browser and checking to see if it works. Your server is most likely behind your network's firewall. You'll need to configure port forwarding to allow external clients to connect.

Can't load image from my local server on Android

I am trying to load an image from a server to show it in an ImageView
I used
ImageView imgView = (ImageView) findViewById(R.id.ivProduct);
Bitmap bitmap = null;
try {
URL urlImage = new URL(
"http://www.google.fr/intl/en_com/images/srpr/logo1w.png");
HttpURLConnection connection = (HttpURLConnection) urlImage
.openConnection();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
imgView.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}`
This worked fine but when I downloaded the same image on my server and I changed the url to
http://localhost:9527/market_helper/img_products/logo1w.png
It did not work.
What is the problem ?
The problem is that in your url the http://localhost:9527 says it is running on a server on your local machine, but when accessing from your Android the http://localhost refers to the device itself.
If you are on the same network you can try access it by replacing the localhost part with your PC's local IP address (for example 192.168.100.6) You can find out what your IP is by typing ipconfig in the command line.
localhost is the loopback adapter on the machine (127.0.0.1) you will probably not be able to use this address from the android app (might work with simulator but I still wouldn't use it).
If you are on the same network, the machine name might work but it depends on what you are using to host the image. If you are using a full blown web server like IIS or something like that you should be good (don't forget to check firewall settings on the server to all incoming connections on the port you use). If you are using something like the VS web server (cassini) then it will not work because it doesn't allow connections from off the box.
If you are not on the same network (like the phone is using cell data) then you will need something publicly addressable (a DNS name or IP that points to your server on the internet). You don't specify what you are using on the server, but there are many hosting solutions out there for free or very cheap that you could use.
Hope this helps!

Categories

Resources