//是否有没有网
public static boolean getNetWoke(Context context){
//得到系统的服务
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//得到网络
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//判断是否有网络
if(networkInfo != null && networkInfo.isConnected()){
return true;
}else{
return false;
}
}
//1.传入URL 2.上下文 3.接口
public static void getdata(final String path, Context context, final JsonBack jsonBack){
//判断网络 true
if(NetWorkUtils.getNetWoke(context)){
//异步请求
AsyncTask<String,Void,String> asyncTask = new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url1 = new URL(path);
//请求
HttpURLConnection httpURLConnection = (HttpURLConnection) url1.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
if(httpURLConnection.getResponseCode() == 200){
//字节流
InputStream inputStream = httpURLConnection.getInputStream();
String string = StreamToString.getString(inputStream);
return string;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//接口回调
jsonBack.getjson(s);
}
};
asyncTask.execute();
}else {
//没网设置网络
NetWorkUtils.setAlertDialog(context);
}
}