Can't load image from my local server on Android - 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!

Related

how to find a localhost using a django server to contact with android device?

I've set up a Django server on ubuntu and I want to get JSON data from it and show them on an android device but I don't know the server name.
I tried 10.0.2.2, localhost, 127.0.0.1 and ip address but none of them worked. like:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet("http://localhost:8000/books/4/?format=json");
try {
HttpResponse response = httpClient.execute(method);
InputStream is = response.getEntity().getContent();
content[0] = IStoString(is);
Log.i("SERVERTEST", content[0]);
} catch (ClientProtocolException r) {
r.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
the code works with other APIs.
The Exception is: connection to http://127.0.0.1:8000 refused
when I test with android device, I do these steps:
1. open device wifi hot spot
2. connect Ubuntu server to device's wifi
3. in Ubuntu terminal, run ifconfig to get IP address
4. run web server on Ubuntu
5. connect from device using IP address from step 3
But I found that I will need to open data connection on the device too, not sure why.
You can use some of these services that will provide a tunnel to your localhost and provide you an externally available URL even with https.
http://localtunnel.me/
https://ngrok.com/
So if you have http://127.0.0.1:8000/my_endpoint
It will be available as https://{provided_url}/my_enpoint from the internet.

Can an app setup with HTTP requests, receive json sent via HTTPS?

I've had a prototype native Android app sitting on my phone for ages, and use it to demo something to people; it's worked 100's times. The app grabs data from a JSON file on a public server and renders it on a map, nothing special.
Now I have an issue, the data isn't loading anymore!
The server is still running, and I can access the JSON file directly in a web browser, it works fine.
All else is the same except recently I re-configured the server to forward all HTTP traffic to HTTPS, using htaccess rules. This was for another project on the server and same domain.
Would this be the likely culprit? Will an Android app, with hardcoded requests to HTTP urls, have problems it's sent a response as HTTPS ?
I would have traced this on my own... however... I LOST THE SOURCE CODE for the app... something I realized months ago and knew some day it would be a problem.
This is the particular htaccess rule that forwards all HTTP traffic to HTTPS.
Can an exception be made for a particular .json file in the root (mywebsite.com/data.json)?
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R,L]
Can you try to make another android application for testing and try to load the JSON using HTTP protocol and if that fails, using HTTPS protocol. Also yes, forcing all http -> https may cause issues (although it may seem normal in web browser) . If HTTP fails, just replace all HTTPURLConnection with HTTPSURLConeection and print the String result.
try {
String result = "";
URL url = new URL(YOUR_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int i = reader.read();
while(i != -1){
result += (char) i;
i = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
Found the answer...
The http-to-https forwarding was the culprit.
I put an exception for my app's data.json (to keep it as HTTP), now the Android app works as usual.
RewriteCond %{SERVER_PORT} 80
RewriteCond %{THE_REQUEST} !/data.json [NC]
RewriteRule ^(.*)$ https://www.mywebsite.com/$1 [R,L]

Connecting to localhost in 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.

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.

POST a Json object from an android app to localhost:9000 using play framework

Well the title says pretty much what I want to do. How can I post a JSON Object to my localhost:9000 (which is started with play framework) from a button click in an Android app. I have done the android method using AsyncTask to Post my JSON object and it works on other APIs. However, I am unsure on how to post it in my localhost:9000 because I want to use the latter as a REST API. Do I have to write something in the routes or configs files in play to be able to receive the JSON object?
For example,
GET /someplace Controllers.applications.index()
If this helps, here is my method for executing the post in android asynctask:
#Override
protected String doInBackground(String... params) {
JSONObject test = new JSONObject();
try {
test.put("Products", params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
String send = test.toString();
send = "Products=" + send;
// localhost is my actual IP address
executePost("http://<localhost>:9000/request",send);
return null;
}
You are using an external/internet ip address. For that you have to configure your router indeed. The router should forward the used port to the pc where your server runs. It is much easier to use the LAN address of the pc as then you don't have to forward. Find out LAN ip of pc with ipconfig.
There are multiple ways to connect your app to localhost. An Easy way is to connect your computer with internet through you mobile (hotspot or tethering).
Open your terminal and run ifconfig and get the IP address provided by the usb connection (tethering). Use this IP instead of (localhost).

Categories

Resources