public class HttpUtil {
public static void AsyncTask(String http, final CallbackString backString){
new AsyncTask<String,Integer,String>(){
@Override
protected String doInBackground(String... strings) {
return Httpget(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
backString.getData(s);
}
}.execute(http);
}
public interface CallbackString{
void getData(String s);
}
public static String Httpget(String httpget){
try {
URL url = new URL(httpget);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code==200){
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String s = "";
while ((s=reader.readLine())!=null){
builder.append(s);
}
return builder.toString();
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean isNetworkConnected(Context context){
if(context!=null){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info!=null){
return info.isAvailable();
}
}
return false;
}
}
Handler网络请求 判断网络状态
最新推荐文章于 2023-07-03 20:04:26 发布