package com.qy.glide;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtil {
//注意工具类中使用静态方法
public static boolean isNetworkConnected(Context context) {
//判断上下文是不是空的
//为啥要判断啊? 防止context是空的导致 报空指针异常
if (context != null) {
//获取连接管理器
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取网络状态mConnectivityManager.getActiveNetworkInfo();
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
//判断网络是否可用//如果可以用就是 true 不可用就是false
return mNetworkInfo.isAvailable();
}
}
return false;
}
\
//=====================================================
public static String requestString(String strUrl) {
try {
//把String 变成URL
URL url = new URL(strUrl);
//打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//连接超时时间
connection.setConnectTimeout(5000);
//读取超时时间
connection.setReadTimeout(5000);
//设置请求方式(要大写)
connection.setRequestMethod(“GET”);
//判断请求码 HttpURLConnection.HTTP_OK
if (connection.getResponseCode() == 200) {
//获取输入流(输入=>读,输出=>写)
//ctrl+alt+V 补全代码
InputStream stream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(stream, “utf-8”);
BufferedReader reader = new BufferedReader(inputStreamReader);
//拼接字符串
StringBuffer buffer = new StringBuffer();
String str = "";
//读取字符串
while ((str = reader.readLine()) != null) {
//拼接字符串
buffer.append(str);
}
return buffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}