How to use DefaultHttpClient on Android? - java

I have made an application and used DefaultHttpClient() to access my local server.
The address looks like this: "http://192.168.1.104:8080/login".
I have successfully used it :)
But problem comes when I am in my university and have connected to the network and have an IP address like: "http://130.230.146.148:8080/login", which I am unable to connect and gets the following error:
java.net.ConnectException: failed to connect to /130.230.146.148 (port 8080): connect failed: EHOSTUNREACH (No route to host).
Although on my pc I can access "130.230.146.148:8080/".
How can I solve this problem?

The EHOSTUNREACH (No route to host) error means that a TCP attempt to connect was made and failed because the underlying protocol software did not find a network node to connect to the targeting node.
When you say that when you are in the university and trying to connect it means that you are probably within a private sub-net. So what you could possibly do is check if your Android device is also connected to that sub-net.

Maybe at university you are under a proxy server, try to find out what are proxy server IP and port (if you can access to the URL through your pc-browser, you have to have the browser configured for the proxy). Once you have it, try this
// Proxy server
HttpHost proxy = new HttpHost("your host", your proxy);
// httpClient is your DefaultHttpClient once instantiated
httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
// If you need credentials, ignore otherwise
httpClient.getCredentialsProvider().setCredentials(
new AuthScope("your host", your proxy),
new UsernamePasswordCredentials(
"your username", "your password"));
Hope helps!
P.D: As others user says HttpClient is deprecated, you may consider move to HttpUrlConnection

Related

Cannot make http GET request on localhost of the android device/emulator

I have made test application to investigate the issue related to http request. It is an android application where I'm making request to localhost:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://127.0.0.1")
.build();
try {
Response response = client.newCall(request).execute();
Log.v("krv", response.toString());
} catch (Exception e) {
Log.v("krv", e.toString());
}
As result on device emulator I have "java.net.ConnectException: Failed to connect to /127.0.0.1:80" exception. With any other request on an external resource(like google.com) all are Ok. Also I have installed IIS. Operating system is Windows 10.
P.S. Really what I need - to be able to make http request on stb device where http server is run(where I have the same problem). I guess both issues have similar reason. Could you give me any advice how to fix/debug my problem...
127.0.0.1 is the loopback address for localhost. But when you're inside an android OS, the localhost or 127.0.0.1 is android itself and that is not where your server is running.
If you want to connect to the host machine, you need to find out the IP address of your host machine (Windows 10) and use that IP address instead of 127.0.0.1.
See How to find your local IP address
However, If you want to refer to the computer which is running the Android emulator, use the IP address 10.0.2.2 instead.

Java HTTP Request on VPN only website

I am trying to build a website parser for one of our internal websites (accessible only from the company network - we get on the network through Cisco AnyConnect VPN).
I can access the site fine in any browser, but not using HTTP requests. Windows network and sharing center shows that I have two active networks:
The actual internet connection
The company network (without internet access).
Default HTTP client gets time out as I suppose it makes a request using the actual internet connection (and the website is not accessible to public), but using this code:
HttpParams params = httpClient.getParams();
params.setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName("10.x.x.x"));
I get the following error:
I/O exception caught when connectiong to /10.x.x.x -> {s} -> https://zzz.com:443: Network is unreachable: connect
Also, might be a stupid test but I have done a HTTP request to a "what is my ip" site and the IP is shown as my Wifi IP not the IP through VPN (which I get when I open browser and browse to a "what is my ip" website). Same thing (wrong IP) when I try this using a gui-less browser (Jaunt or HTMLUnit).
Please advise if any fixes for this.
ConnRoutePNames appears to be deprecated. See if the following works (I haven't tested):
HttpHost proxy = new HttpHost("10.x.x.x", 80);
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();

Accessing Servlet from android httpclient programs getting connection refused?

While I access the localhost servlet from android httpclient utils I am getting connection refused error. The servlet is running fine, but I am getting error.
This is the code:
String dmurl="http://127.0.0.1:9090/DataManagerProject/DMServlet";
HttpClient httpClient = new DefaultHttpClient();
HttpGet hrtreq = new HttpGet(dmurl);
HttpResponse resp = httpClient.execute(hrtreq);
String output = EntityUtils.toString(resp.getEntity());
I am getting following error org.apache.http.conn.httphostconnectexception connection to refused
if you are using emulator to run your app for local server. mention the local ip as 10.0.2.2 and have to give Internet permission into your app
For more details, please refer this link.
Also, Turn Off the firewall and any anti-virus application in your PC
Check whether you have internet access enabled in your emulator and in your application
<uses-permission android:name="android.permission.INTERNET"/>
To access internet data of the device or emulator from your application add the above line in your manifest xml file.Also check the servlet mapping is proper in your the servlet project.
Assuming your servlet runs on your computer the reason you can't get a connection is because your using the wrong IP. 127.0.0.1 is a loopback address meaning that if you connect to 127.0.0.1 on your Android device, it will try to connect to the Android device.
To make it work you have to find the IP address of the computer which runs the servlet and use that in the URL instead.
In addition make sure you have given the Internet permission to your app.

java and access error when connecting to the database

Today I encountered the following problem. When connecting to a database, the following error.Appeal to the remote database by connecting through vpn.
Added necessary firewall ports and even tried to disconnect its(did not help)
Added record to $JAVA_HOME/jre/lib/security/java.policy
grant codeBase "file:/-" {
permission java.security.AllPermission;
};(did not help)
If trying to connect with same data through sql management studio, it works and there is access. from the development environment no connection
Example(string connection = jdbc:sqlserver://DEVMSSQL14.test.com:1433;SCHEMA=test;DATABASENAME=test, sql managment studia = DEVMSSQL14.test.com,1433)
on another computer it works without problems, the same version of the project
It remains only to "Permission denied: connect".Maybe somebody faced with similar
Error:
The TCP/IP connection to the host DEVMSSQL14.test.com, port 1433 has failed. Error: "Permission denied: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
In the error message, you have shown like DEVMSSQL14.test.com, 1433 has failed.
I believe, it is correct. I dont think. this host name is correct. which says "TEST" as domain
Open the cmd, try to ping DEVMSSQL14.test.com
Success case :
If you are able to ping, then make sure the services are running for sql in services
Failure case:
Get the right host name to establish the connection
When i tried, i got this message, because i may be out of network.
Pinging DEVMSSQL14.test.com [208.64.121.161] with 32 bytes of data:
Request timed out.
Request timed out.
Try setting a System Property while running the code.
The catch is to introduce this line in code: System.setProperty("java.net.preferIPv4Stack", "true");
Or to pass it in VM option: -Djava.net.preferIPv4Stack=true

Connect to FTPS through proxy

The initial problem we encountered was that a regular FTPs download started failing due to an untrusted server certificate. This prompted us to wonder whether the certificate had been updated without the counterparty notifying us so we wanted to download the current certificate and compare it to the one we have in our keystore.
This seems to be a trickier problem than we had anticipated. The usual suspects (firefox, filezilla, ...) did not seem up to the task of connecting to an FTPs server through an FTP proxy so out of curiosity I started playing around with a more low level java approach. I can not for the life of me get it to work though.
First (overly simplistic) java attempt:
// create proxy connection
SocketFactory plainFactory = SocketFactory.getDefault();
Socket proxy = plainFactory.createSocket(proxyServer, proxyPort);
// create ssl connection on top of it?
SSLSocketFactory sslFactory = getSocketFactory();
SSLSocket socket = (SSLSocket) sslFactory.createSocket(proxy, server, port, true);
This approach obviously does not work.
Next I started playing around with ftp4j (http://www.sauronsoftware.it/projects/ftp4j/) it seems to have a clean and accessible codebase:
FTPClient client = new FTPClient();
client.setConnector(new FTPProxyConnector(proxyHost, proxyPort));
client.getConnector().setConnectionTimeout(0);
client.getConnector().setReadTimeout(0);
client.setSSLSocketFactory(getSocketFactory());
// also tried SECURITY_FTPS
client.setSecurity(FTPClient.SECURITY_FTPES);
client.connect(server, port);
This outputs:
REPLY: 220 Blue Coat FTP Service
SEND: USER anonymous
REPLY: 530-User Access denied.
REPLY: 530-
REPLY: 530-Usage: USER username#hostname
REPLY: 331 PASS userpassword
Exception in thread "main" java.io.IOException: Invalid proxy response
The proxy server has optional authentication and on our development servers we generally use "user#host" without proxy authentication. As such I assume the username, hostname and password are those of the remote server?
So I tried adding the remote parameters, this does not work:
REPLY: 220 Blue Coat FTP Service
SEND: USER test#ftps.example.com
Exception in thread "main" java.io.IOException: FTPConnection closed
Adding the proxy user to match the bluecoat format does not seem to work either:
USER %u#%h %s
PASS %p
ACCT %w
Any help with either of these two problems would be most welcome:
how to retrieve the server certificate from an ftps server through an ftp proxy
how to connect to an ftps server through an ftp proxy in java
You might want to try Apache Net commons libs.
Here is a similar thread that uses that Net Commons library
Net commons also has a fully functional FTP Client Example so you can test with something you know works.

Categories

Resources