I know how to check internet connectivity (NetworkInfo::isAvailable, isConnected) but I've got problems with hotspots.
When you're connected to a hotspot but you didn't enter the password, you are connected to the internet (so the regular check will return true), but you can't connect to sites.
I there a way to confirm that I didn't pass the hotspot's password check? maybe ping to some server?
Would checking a HTTP response code work for you?
String urlFeed = "your_url.com";
URL url = new URL(urlFeed);
URLConnection urlConnection;
urlConnection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
int responseCode = httpConnection.getResponseCode();
And then check the response code for a negative response?
Related
To put data into a database I use a GET-request. I tried to send one from within Android to my server, but the data I sent, did not appear in the database. Then I just added httpURLConnection.getResponseCode(); and everything got working fine.
So, the following is not working until the last string is uncommented
try {
URL url = new URL(urlString);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
//httpURLConnection.getResponseCode();
}
My question: Why does the request get sent only if I call getResponseCode?
I create an HttpURLConnection in a Thread or AsyncTask and it works fine.
But when the Device is in sleep mode, (Display is Off...) then I get an
Exception by open the Connection -> java.net.ConnectException: Connection refused.
My idea is to wake up the Device with the PowerManager.PARTIAL_WAKE_LOCK, but that doesn't help.
The other defines from PowerManager for example ACQUIRE_CAUSES_WAKEUP are deprecated.
What can I do to create a successful connection?
The code:
URL url = new URL("myUrl...");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
int response = urlConnection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
// to do some work
}
I suggest you to use OkHttp. It is better than HttpClient.
I'm trying to parse the json data from an url, when i try to create connection , it throws the exception as
java.net.ProtocolException: cannot write request body after response has been read
I got the response message as Not found.
and i checked the url in web browser it shows the Json data when i login wuth my credentials.
so, i found that i need to add the cookie to my connection, but i don't know how to do this.
public void parseData(String cookie){
HttpUrlConnection connection;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Cookie", cookie);
Log.e(TAG, "cookie " + cookie);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
Log.e(TAG,connection.getResponseMessage());
/**
here i'm trying to parse the data
using BufferedReader calss
**/
}
catch(IOException e){}
}
i need to add the cookie in connection.
Please help me on this.
According to this link
you can do this:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request: Using the
setRequestProperty(String name, String value); method, we will add a
property named "Cookie", passing the cookie string created in the
previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server: To send the cookie, simply call connect() on the URLConnection
for which we have added the cookie property:
urlConn.connect()
In my android Application in the first screen user authenticates and servlet replies with a session id ...
in the second screen the user again calls the servlet with the session id added in the url as ;jsession="sessionid" along with the parameters...
but the servlet is not get the session id and is responding as a new session without authentication...
where is the problem?
i am using this code for the connection
URL u = new URL(aurl[0]);
url=aurl[0];
publishProgress(""+20,"Connecting...");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
publishProgress(""+40,"Connecting...");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
publishProgress(""+45,"Connecting...");
publishProgress(""+40,aurl[0]);
int lenghtOfFile = c.getContentLength();
System.out.println(lenghtOfFile+"lenghtOfFile");
is = c.getInputStream();
I was facing the same problem and found a simple solution.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
This is the simplest solution I found. We need to set default CookieManager.
Using java.net.URLConnection to fire and handle HTTP requests is the great blog.
Thanks
adding jseesioid in the url never worked ..
the code worked using this solution
httpsessionmanagement
especially these two...
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
I have a code to perform POST Requests with HttpsUrlConnection, the code works fine, but some of my Users have SIM Cards with a closed Usergroup and they need to set a proxy in the settings of their apn. If they set the proxy, i need to modify my code. I Tryed this:
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = "https://xxx";
String boundary = "*****";
try {
URL url = new URL(urlServer);
SocketAddress sa = new InetSocketAddress("[MY PROXY HOST]",[My PROXY PORT]);
Proxy mProxy = new Proxy(Proxy.Type.HTTP, sa);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + boundary);
//this is supposed to open the connection via proxy
//if i use url.openConnection() instead, the code works
connection = (HttpsURLConnection) url.openConnection(mProxy);
//the following line will fail
outputStream = new DataOutputStream(connection.getOutputStream());
// [...]
} catch (Exception ex) {
ret = ex.getMessage();
}
now i receive the error:
javax.net.ssl.SSLException: Connection closed by peer
If i use url.OpenConnection() wuithout Proxy and without Proxysettings in the apn, the code works, what might be the Problem?
You could try this alternative way of registering a proxy server:
Properties systemSettings=System.getProperties();
systemSettings.put("http.proxyHost", "your.proxy.host.here");
systemSettings.put("http.proxyPort", "8080"); // use actual proxy port
You can use the NetCipher library to get easy proxy setting and a modern TLS config when using Android's HttpsURLConnection. Call NetCipher.setProxy() to set the app-global proxy. NetCipher also configures the HttpsURLConnection instance to use the best supported TLS version, removes SSLv3 support, and configures the best suite of ciphers for that TLS version. First, add it to your build.gradle:
compile 'info.guardianproject.netcipher:netcipher:1.2'
Or you can download the netcipher-1.2.jar and include it directly in your app. Then instead of calling:
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection(mProxy);
Call this:
NetCipher.setProxy(mProxy);
HttpURLConnection connection = NetCipher.getHttpURLConnection(sourceUrl);