In the logcat I get a warning:
W/System: A resource failed to call end.
I am 100% positive that this piece of code makes the warning, since when I take it out it stops.
I can't seem to fix it so it doesn't display warning.
The purpose of the code is to check if there is internet connection or not.
It is on separate thread. Declared with:
public class ConnectWifiThread extends Thread {
public static boolean isInternetAvailable(Context context) {
Here is the code:
try {
URL url = new URL("https://www.google.com/");
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setRequestProperty("User-Agent", "test");
https.setRequestProperty("Connection", "close");
https.setConnectTimeout(2000); // mTimeout is in seconds
https.connect();
int tempResponse = https.getResponseCode();
if (tempResponse == 200) {
https.disconnect();
Thread.sleep(50);
https=null;
url=null;
Thread.sleep(50);
Log.d("Has", "internet");
return true;
} else {
https.disconnect();
Thread.sleep(50);
https=null;
url=null;
Thread.sleep(50);
Log.d("NO", "internet");
return false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
catch (Exception e) {
Log.d("Error checking internet", e.getMessage());
return false;
}
Thank you
When you use a URLConnection, by default it makes an input stream for you to read the response. You'd get that by calling getInputStream() on the connection, and then you'd read the stream to completion and close it.
If you don't need the data, you can alternatively call setDoInput(false) to save you the trouble of doing the above.
Related
I am trying to check if internet is on or not constantly every 5 seconds, I wrote below code but some how it always go inside wait() and waiting infinite.
Code I wrote :
Socket socket = null;
public void checkInternetConnectivity() throws InterruptedException {
boolean reachable = false;
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
try {
socket = new Socket("xxx.xxx.xxx.x", xx);
} catch (UnknownHostException e) {
stopApp();
} catch (IOException e) {
stopApp();
}
}
}, 0, 5, TimeUnit.SECONDS);
synchronized (this) {
wait();
}
}
private void stopApp() {
System.out.println("Internet Not Available stopping app");
System.exit(0);
}
It always stuck inside below :
synchronized (this) {
wait();
}
You could do:
InetAddress.isReachable
Depending on what your needs are you should consider trying reach a specific host by
private static boolean googleIsAvailable() {
try {
final URL url = new URL("http://www.google.com");
final URLConnection connection = url.openConnection();
connection.connect();
connection.getInputStream().close();
return true;
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
return false;
}
}
If your are communicating with a webservice the webservice should provide a GET method to check if it is available.
If you need to check constantly try somthing like
Socket s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
while(s.isConnected()){
//do your stuff
}
You should also check out the keepAlive Option.
But the more important question is what happen in your application if internet connection is not available anymore?
Most methods throw Exceptions if a Server is not available anymore.
You could just catch them and react on it.
I am looking to test to see if hundreds of URLs exist, and the current way I have takes too much time. This is what I have found so far:
public static boolean checkURL(URL u)
{
HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) u.openConnection();
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
// You can determine on HTTP return code received. 200 is success.
if (code == 200)
{
return true;
}
else
{
return false;
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("error");
}
catch (IOException e)
{
System.out.println("error2");
// TODO Auto-generated catch block
// e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
return false;
}
Although this does successfully find whether a URL exists and has content, it does so in a lengthy period of time, with the program often taking upwards of five minutes to execute. Does anyone know more efficient ways to test this?
Note: It is important to test that not only the url returns 200, but also that the website doesn't timeout.
Your code looks good and it should be the easiest way to check for url. You might want to add a timeout in the HttpURLConnection.
Sample code for reference.
enter code here
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlChecker {
public static void main(String[] args) {
System.out.println(URLExists("http://slowwly.robertomurray.co.uk/delay/
3000/url/http://www.google.co.uk"));
}
public static boolean URLExists(String targetUrl) {
HttpURLConnection urlConnection;
try {
urlConnection = (HttpURLConnection) new
URL(targetUrl).openConnection();
urlConnection.setRequestMethod("HEAD");
// Set timeouts 2000 in milliseconds and throw exception
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
/* Set timeouts 4000 in milliseconds and it should work as the url
should return back in 3 seconds.
httpUrlConn.setConnectTimeout(4000);
httpUrlConn.setReadTimeout(4000);
*/
System.out.println("Response Code =>"+
urlConnection.getResponseCode());
System.out.println("Response Msg =>"+
urlConnection.getResponseMessage());
return (urlConnection.getResponseCode() ==
HttpURLConnection.HTTP_OK);
} catch (Exception e) {
System.out.println("Exception => " + e.getMessage());
return false;
}
}
}
Upon trying to connect to a host/server that does not exist, my program just seems to die. Stepping through with the debugger lends me nothing, it makes it to getResponseCode() and then just stops working. No exceptions are thrown from what I can tell and the program doesn't return.
Here is the relevant code snippet:
try {
//construct a URL and open the connection
URL url = new URL("http://" + serverHost + ":" + serverPort + urlSuffix);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
if(http.getResponseCode() != 200) {
System.out.println("Could not connect");
}
System.out.println("Connected");
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
} catch (IOException e) {
e.printStackTrace();
return;
} catch (Exception e) { //give me something please
e.printStackTrace();
return;
}
When connecting to a valid URL, it works fine.
I fixed it, I needed to add http.setConnectTimeout(10000); after I opened the connection. Apparently whatever the default timeout was set as was so long that it appeared to never give a response at all, even when leaving the application open for several minutes.
I added in the MainActivity a button click event:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
try
{
response = Get(ipaddresses[i]);
break;
} catch (Exception e)
{
text.setText("Connection Failed");
}
}
if (response!=null)
{
String a = null;
try
{
a = new String(response,"UTF-8");
text.setText(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
});
t.start();
}
});
}
I wanted to create a break when it's entering the try block after doing the response = Get(ipaddresses[i]); in order to stop the for loop.
The problem is that after it's done the response = Get(ipaddresses[i]); when it's supposed to be doing the break, my program crashes.
On the android device I get the message:
unfortunately myapp has stopped
And when I click ok on the message the program just closes.
I can't figure out why the break makes the program crash.
This is the Get method:
private byte[] Get(String urlIn)
{
URL url = null;
String urlStr = urlIn;
if (urlIn!=null)
urlStr=urlIn;
try
{
url = new URL(urlStr);
} catch (MalformedURLException e)
{
e.printStackTrace();
return null;
}
HttpURLConnection urlConnection = null;
try
{
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] buf=new byte[10*1024];
int szRead = in.read(buf);
byte[] bufOut;
if (szRead==10*1024)
{
throw new AndroidRuntimeException("the returned data is bigger than 10*1024.. we don't handle it..");
}
else
{
bufOut = Arrays.copyOf(buf, szRead);
}
return bufOut;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
finally
{
if (urlConnection!=null)
urlConnection.disconnect();
}
}
The reason for the crash is most likely apparent from the stacktrace that you haven't shown us.
But the logic of that loop is pretty dubious ... to me.
Without the break, the loop iterates over all of the IP addresses, and tries Get on each one. At the end, response will be the last value returned by a Get call, which may or may not be null.
With the break, the loop terminates after the first IP address for which Get doesn't throw an exception ... irrespective of what the Get call returns. (That could be null.)
These could be the cause of your crash, but it could be something else. Either way, the logic is suspicious. (And calling a method Get is bad style!)
UPDATE
Given that the Get method catches exceptions and returns null on failure, the recommended structure for the code that calls it is:
for (int i = 0; i < ipaddresses.length; i++) {
response = Get(ipaddresses[i]);
if (response != null) {
break;
}
}
if (response == null) {
// notify connection failed
} else {
// process response
}
There is not need for a "belt and braces" try {...} catch in the calling code ... if you have already dealt with the expected exceptions in Get. And (IMO) you should (almost) never catch Exception, because that is liable to conceal bugs.
I have a class called RetreiveHttpStringResponse. It's used to get an InputStream from an URL containing JSON data. The class extends AsyncTask<String, Void, InputStream>. So the strange problem here is that null is always returned. No matter what. There is even no Exception. I checked out the program behaviour with the debugger and could see that at point (1) the processing is jumping immediately to the finally-statement and continues with return null;. And again there are no Errors and no Exceptions are going on. The programm is running normally.
I'm using Android 4.4 (SDK version 19), the response code is 200 and the following lines are set in the Manifest file.
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
The problem is happening on the emulator and on a real device with internet connection. Here is the code:
#Override
protected InputStream doInBackground(String... arg0) {
URL url = null;
InputStream is = null;
HttpURLConnection urlConn = null;
int responseCode = 0;
try {
url = new URL(arg0[0]);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("GET");
urlConn.connect();
responseCode = urlConn.getResponseCode();
Log.d("DataHandlerInternet:RESPONSE_CODE", "The response is: " + responseCode);
is= urlConn.getInputStream(); //-->(1)<--
return is;
}
catch ( MalformedURLException e ) { // new URL() went wrong!
//TODO error message. URL is not correct!
e.printStackTrace();
}
catch (SocketTimeoutException e) { // Timeout while connecting or holding connection to URL.
//TODO error message. Timeout happened!
e.printStackTrace();
}
catch ( IOException e ) { // openConnection() failed!
//TODO error message. Couldn't connect to URL!
e.printStackTrace();
}
catch( Exception e ) { // Any other Exception!
e.printStackTrace();
}
finally {
try { if(is != null) { is.close(); } } catch(Exception e) {e.printStackTrace();}
try { if(urlConn != null) { urlConn.disconnect(); } } catch(Exception e) {e.printStackTrace();}
}
return null;
}
One bad solution is to delete the finally-statement. Well, not the best way to solve this problem.
Now I changed the code. I've put the reading in it and return just the String.
#Override
protected String doInBackground(String... arg0) {
URL url = null;
InputStream is = null;
HttpURLConnection urlConn = null;
int responseCode = 0;
try {
url = new URL(arg0[0]);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setReadTimeout(10000);
urlConn.setConnectTimeout(15000);
urlConn.setRequestMethod("GET");
urlConn.connect();
responseCode = urlConn.getResponseCode();
Log.d("DataHandlerInternet:RESPONSE_CODE", "The response is: " + responseCode);
is= urlConn.getInputStream();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ( (line = br.readLine()) != null ) {
sb.append(line);
}
return sb.toString();
}
catch ( MalformedURLException e ) { // new URL() went wrong!
//TODO error message. URL is not correct!
e.printStackTrace();
}
catch (SocketTimeoutException e) { // Timeout while connecting or holding connection to URL.
//TODO error message. Timeout happened!
e.printStackTrace();
}
catch ( IOException e ) { // openConnection() failed!
//TODO error message. Couldn't connect to URL!
e.printStackTrace();
}
catch( Exception e ) { // Any other Exception!
e.printStackTrace();
}
finally {
try { if(is != null) { is.close(); } } catch(Exception e) {e.printStackTrace();}
try { if(urlConn != null) { urlConn.disconnect(); } } catch(Exception e) {e.printStackTrace();}
}
return null;
}
And still, after going through the while loop the return line; is completely ignored. I've checked the data in the String with the debugger and it was correct! No Errors no Exceptions.
finally will run in either case, also during normal return without exceptions. And you call .close in the finally statement clause.
So your code always returns the closed stream. Probably this is not that you intend.
Your description ("jumps to finally statement") still looks very much like a exception has been thrown by urlConn.getInputStream(). Strange you do not observe it.
I dont see why you get your null result but, one thing you are doing wrong is actually returning InputStream:
is= urlConn.getInputStream(); //-->(1)<--
return is;
you should read your stream in doInBackground (on worker thread), otherwise reading it in onPostExecute (UI Thread), will possibly cause NetworkOnMainThreadException, or at least ANR. Reading data from InputStream is still a network operation - data you download can be several MBs.