StatusReader/src/net/indivia/hacklabbo/statusreader/SNetwork.java
2015-04-09 20:31:32 +02:00

99 lines
No EOL
2.8 KiB
Java
Executable file

package net.indivia.hacklabbo.statusreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.annotation.TargetApi;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.StrictMode;
import android.util.Log;
public class SNetwork {
public static final String LOG_TAG = "SNetwork";
public static boolean isConnected(ConnectivityManager cm) {
boolean connected = false;
if (cm != null) {
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
Log.d(LOG_TAG, "type:"+ni.getTypeName()+" conn:"+ni.isConnected()
+" avv:"+ni.isAvailable() );
if ((ni.getTypeName().equalsIgnoreCase("WIFI") ||
ni.getTypeName().equalsIgnoreCase("MOBILE"))
&& ni.isConnected() && ni.isAvailable()){
connected = true;
break;
}
}
}
return connected;
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static String GET(String uri){
String result = "";
HttpURLConnection con;
try {
con = (HttpURLConnection) ( new URL(uri)).openConnection();
try {
con.setRequestMethod("GET");
con.setDoOutput(false);
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
con.connect();
InputStream is = con.getInputStream();
if(is != null)
result = convertInputStreamToString(is);
else
result = "Did not work!";
con.disconnect();
} catch (IOException e) {
Log.d(LOG_TAG,"no json");
result = "Il file json non esiste";
e.printStackTrace();
}
} catch (ProtocolException e1) {
Log.d(LOG_TAG,"protocoll");
e1.printStackTrace();
}
} catch (MalformedURLException e2) {
Log.d(LOG_TAG,"mal url");
result = "Manca il protocollo";
e2.printStackTrace();
} catch (IOException e2) {
Log.d(LOG_TAG,"IO 2");
e2.printStackTrace();
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
String line = "", result = "";
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}